This article was written on May 13, 2020
Recently, as the code was writing, it occurred to me — why do we need async and await when we already have promises and then?
This is not pants farting?
Let’s say we need code to request a server:
new Promise((resolve, reject) = > {
setTimeout((a)= > {
const res = "When will the moon be?"
if (1 > 2) {
resolve(res)
} else {
reject('I don't know. Ask the sky.')}},1500)
}).then(
(res) = > {
console.log('It worked! As a result,${res}`)
},
(err) => {
console.log('Failed... The error is${err}`)})Copy the code
If you don’t understand, you can read an article I wrote earlier. What is Promise?
This code, neat and nice, but if async and await are used, it should look like this:
function ask() {
return new Promise((resolve, reject) = > {
setTimeout((a)= > {
const res = "When will the moon be?"
if (1 > 2) {
resolve(res)
} else {
reject('I don't know. Ask the sky.')}},1500)})}async function test() {
try {
const res = await ask()
} catch (err) {
console.log(err)
}
}
test()
Copy the code
You even need a try catch to catch errors! The more I write it, the more IT looks like Java.
MDN gives us some explanations:
If you use asynchronous functions in your code, you will find that the syntax and structure of asynchronous functions are more like standard synchronous functions.
To put it bluntly, part of the reason for this is to “please” Java and other programmers.
On the other hand, it also enhances readability. Although the expression async await is ugly, there is no doubt that it is much more readable than Promise then.
Most importantly, promises can be nested indefinitely, while async await can only handle one Promise and cannot continue nesting.
So once you need to use multiple consecutive callbacks, async await becomes tired.
It is also possible to await a promise.all ().
(after)