Subject. Can I say that two pieces of code below are equal:
await someFunc() // no assignment here
doSomethingAfterSomeFunc()
and:
someFunc().then(() =>
doSomethingAfterSomeFunc()
)
I tried and it looks like they are equal but there is a doubt(e.g. some optimization)
The await expression causes async function execution to pause until a promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled promise.
await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves. So, if an asynchronous activity has already started, await will not have an effect on it.
This rule applies when the await operator is used on a non-Promise value. await operator pauses the execution of the current async function until the operand Promise is resolved.
Otherwise, if you don't use it, nothing good or bad will happen by default - the code inside the promise will still run, but nothing will happen when you call resolve . If you call reject , however, then nothing will handle the rejection; which is bad, as it throws an error on most platforms.
To expand on Dan D's answer (because it took me a while to figure out myself), I'll say a few more things about execution flow. Indeed, using await
blocks the flow of the method it's called in until it resolves. Let's say we have this async function:
const someFunc = (str) => {
return new Promise(resolve => {
setTimeout(() => {
console.log('resolving promise')
resolve()
}, 1500)
})
}
So if we call with await, like this:
console.log('before calling')
await someFunc()
console.log('after calling')
we get the following result:
before calling
resolving promise
after calling
However, when we use .then()
:
console.log('before then')
someFunc().then(() => console.log('resolved'))
console.log('after then')
this happens:
before then
after then
resolving promise
resolved
This is because .then()
does not stops the execution flow and runs next function in the chain only when the previous promise is finished. Sometimes you want this to happen, sometimes you don't, sometimes it doesn't matters. But if you don't know about this, it can take some time to figure it out. So I hope this example will help you understand it.
Yes they are exactly the same, it's more or less syntactic sugar. The await causes execution to pause until the awaited Promise
is resolved.
See Javascript async the section on rewriting a promise chain for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With