What is async doing?
- Async is short for async, which means this method is asynchronous
- The async function returns a Promise object
- If an async function returns a value, async wraps the value into a promise object with promise.resolve()
- Resolve (undefined) if no value is returned
Await what?
- Await an async function. The syntax says await an expression, either an expression or a promise object
- If await waits for a promise object, await suspends the code behind async, executes the code outside async first, and takes the resolve argument as the result of await
- If it is not a promise object, it will block execution and treat non-promise expressions as await expression results
Use of async and await
- The chain call of promise, parameter transfer is more troublesome
function newData() {
return new Promise(resolve => {
resolve(1);
})
.then(result => console.log(result)) //1
.then(result => {
console.log(result); //undefined
return 2;
})
.then(result => {
console.log(result); //2
throw new Error("err");
})
.then((result) =>{
console.log(result);
}, (err)=>{
console.log(err); //Error: err
return 3;
})
.then((result) => {
console.log(result); //3
})
}
newData();
Copy the code
- To simplify promise operations use async and await
function newData(ms) { return new Promise(resolve => { setTimeout(resolve, ms); }) async data2(value,ms) { await newData(ms); } data2('xiaoming',50); // every 50ms xiaoming}Copy the code
conclusion
With async/await, along with promise, you can improve code simplicity and readability by writing code that looks like synchronization to handle asynchronous processes.
Advantages of async await:
- Fixed callback hell
- Support concurrent execution
- You can add the return value return XXX;
- You can add try/catch to your code to catch errors
What does async do?
Define an asynchronous function (usually with asynchronous operations inside) that returns a Promise object, the Promise of return if a Promise is returned, and the return value in Promise.resolve otherwise
What is await waiting for?
It can only be placed in async functions and wait for the result of the expression on the right-hand side, which is a return value if it is a function, or a string if it is a string
What is the use of “await”?
Block the following code, first executes the async external synchronization code, then returns to async, gets the result of the operation, returns a promise, waits for the promise object, and uses the resolve parameter as the result of the expression, not the promise