Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

javascript - Order of operations after promises

I'm pretty new to JavaScript (using Node.js) and still learning. I try to wrap around my head with promises and I got into this situation where I don't understand if there is a difference between this code:

promiseFunc().then(() => {
     anotherPromiseFunc() // I dont need .then() here, just want to save some data to DB
 });
doSmthElse()

and this code:

promiseFunc().then(async () => {
     await anotherPromiseFunc() // I dont need .then() here, just want to save some data to DB
 });
doSmthElse()

If I don't use .then() in the first case, does it mean there is a possibility that doSmthElse() will be executed before anotherPromiseFunc() is executed? So in order to prevent that, I have to add async/await? Or all code in .then() block is being waited to execute anyway before doing something else?

Note 1: I don't want to chain those promises, because there is more code in my case, but I just simplified it here.

Note 2: I don't use catch because if error will rip through I will catch it later.

question from:https://stackoverflow.com/questions/65644068/order-of-operations-after-promises

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I don't use .then() in the first case, does it mean there is a possibility that doSmthElse() will be executed before AnotherPromise() is executed?

doSmthElse() is guaranteed to be executed before anything in the fulfillment handler1 is executed. Promise fulfillment and rejection handlers are always invoked asynchronously. That's true whether you declare the handler function using async or not.

For example:

console.log("before");
Promise.resolve(42)
.then(result => {
    console.log("within", result);
});
console.log("after");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...