I like to keep records in the learning process and share my accumulation and thinking on the way to the front end. I hope to communicate with you and make progress together. This is my
Making a blog, welcome to star
Async is a function proposed by ES7, which is known as the best solution of JS asynchronous operation so far
The async function is the syntactic sugar of the Generator and the await command is the syntactic sugar of the internal THEN command.
Async is represented with the keyword async and await is used inside the function.
I. Improvements over Generator
1. Built-in actuator
The execution of Generator functions must depend on the executor, whereas Aysnc functions have their own executor and are called in the same way as normal functions
2, better applicability
By convention of the CO module, a yield command can only be followed by a Thunk function or a Promise object. The await command of async functions can be followed by a Promise or a primitive value (Number, string, Boolean, but this is equivalent to a synchronous operation).
The return value is Promise
Async functions return Promise objects, which are more convenient than iterators returned by Generator functions and can be called directly using the then() method
2. Use of Async
This is the part where I can’t think of anything to write and for those of you who know Promise and Generator, this is the part that can be solved in five seconds, right
Async error handling
Await can directly obtain the parameters passed by the subsequent Promise success state, but cannot capture the failure state
But, Promise can run as reject, so it’s better to put await in try… In the catch block
async function foo() {
try {
return await dosomething()
} catch (err) {
console.log(err)
}
}
Copy the code
When an async function has an await state, the following await is not executed.
Iv. Notes for Async
Await can only be used within async functions, with promises only, not for callbacks
2. Async operations after Await should be triggered at the same time if they do not depend on each other
async function foo() {
let a = await request(url1);
let b = await request(url2);
let c = await request(url3);
return a + b + c
}
Copy the code
There is no connection between a, B, and c, which should be executed concurrently with promise.all ()
async function foo() {
let results = await Promise.all([request(url1),request(url2),request(url3)])
return results.reduce((total,item) => total * item)
}
Copy the code
How to use async
After all, the ES7 syntax is still relatively new and requires the following support from Babel: Just set the presets to stage-3
npm install babel-preset-es2015 babel-preset-stage-3 babel-runtime babel-plugin-transform-runtime
Copy the code
Modify the. Babelrc file
"presets": ["es2015"."stage-3"]."plugins": ["transform-runtime"]
Copy the code