Is there any differences between async/await, and more standard promise notations using .then
, .finally
, and .catch
for example
functionThatReturnsPromise(someVar).then((returnedValueFromPromise) => {
console.log(returnedValueFromPromise)
})
vs
async functionThatReturnsPromise(someVar) {
await returnedValueFromPromise
}
I'm unsure if Promise chaining is just the old notation, and it's been replaced by the newer async/await. Is there still a use case for both? What is better practice?
It all depends on what you want. async
/ await
are new. Think of it this way, they allow a promise to run like it was synchronous when it isn't.
Moreover using async
/ await
makes your code cleaner and more readable. And to answer your question, there are not much differences between them in terms of what they do. The syntax is just quite different.
Promise chaining is not old fashion, they are quite new, just that async
/ await
came a bit later - giving you a "better" way of handling Promises.
Finally, you can use them interchangeably in your code.
You're misunderstanding how it works. With async/await
you have a synchronous syntax flow of the code execution that's it:
try {
const returnedValueFromPromise = await functionThatReturnsPromise(someVar);
} catch (err) {
console.error(err);
throw err
}
Notice that
async
scoped functionasync
enclosed function are promises by default使用await
需要注意的是,您需要将await
语句包装在try catch block
中,以防请求失败,我个人认为这比常规的 promise 链接更丑陋。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.