async
Async /await is actually syntactic sugar for Generator. As the name implies, the async keyword represents an asynchronous operation in a subsequent function, and await means to wait for an asynchronous method to complete. To declare an asynchronous function, add the keyword async in front of the normal function, for example:
async function funcA() {}Copy the code
Async returns a Promise object (if the specified return value is not a Promise object, a Promise is returned, but resolve immediately, the same way as the then method), so async returns the value, Becomes an argument to the then method’s callback function:
async function funcA() {
return 'hello! ';
}
funcA().then(value => {
console.log(value);
})
// hello!Copy the code
A single async function does exactly the same thing as Promise, so let’s see what await does next.
await
As the name implies, ‘await’ is an asynchronous wait that is waiting for a Promise, so an ‘await’ should be followed by a Promise object that, if not a Promise object, will be converted to an immediately resolve Promise. An async function is immediately executed when it is called, but returns as soon as it encounters await, waits for the asynchronous operation to complete, and then executes the following statement in the function body. To summarize: async calls do not block code, but await calls block code inside async functions. Consider the following example:
async function func() {
console.log('async function is running! ');
const num1 = await 200;
console.log(`num1 is ${num1}`);
const num2 = await num1+ 100;
console.log(`num2 is ${num2}`);
const num3 = await num2 + 100;
console.log(`num3 is ${num3}`);
}
func();
console.log('run me before await! ');
// async function is running!
// run me before await!
// num1 is 200
// num2 is 300
// num3 is 400Copy the code
Async func: async function is running! ‘, the function returns and executes the synchronization task after func(). After the synchronization task is finished, the function continues to await the position. It can be said that async functions can be viewed as multiple asynchronous operations wrapped as a Promise object, and await commands are syntactic sugar for internal THEN commands.
As soon as the Promise state behind await changes to Rejected, the async function will abort. In order to save the error location and error information, We need to use try… The catch statement encapsulates multiple await procedures as follows:
async function func() {
try {
const num1 = await 200;
console.log(`num1 is ${num1}`);
const num2 = await Promise.reject('num2 is wrong! ');
console.log(`num2 is ${num2}`);
const num3 = await num2 + 100;
console.log(`num3 is ${num3}`); } catch (error) { console.log(error); } } func(); // num2 is wrong!Copy the code
As shown above, we get an await at num2 with a Promise object in the rejected state. The error is passed to the catch statement so that we can locate the error.
How is async/await better than Promise?
Let’s rewrite an example of sayHi from the Promise chapter with async/await:
function sayHi(name) {
return new Promise((resolved, rejected) => {
setTimeout(() => {
resolved(name);
}, 2000)
})
}
async functionSayHi_async (name) {const sayHi_1 = await sayHi(name) console.log(' Hello,${sayHi_1}`)
const sayHi_2 = await sayHi('bill') console.log(' Hello,${sayHi_2}`)
const sayHi_3 = await sayHi('Wang Er Ma Zi') console.log(' Hello,${sayHi_3}`)
}
sayHi_async('Joe') // Hello, Zhang SAN // Hello, Li Si // Hello, Ma Zi Wang ErCopy the code
Compared to the long THEN chain and the callbacks in the THEN method, this looks like synchronous writing and is cleaner and more conventionally programmed.