The ES8 that came out soon included the async function, and it finally gave JavaScript the ultimate solution for asynchronous operations. No more callback hell.
The async function is the syntactic sugar of the generator function. Use the keyword async to represent asynchronous using await inside the function.
The improvement over the Generator,async function is the following four points:
* built-in actuator . The execution of the generator function must depend on the executor, and the AYSNC function takes the executor and invokes the same way as a normal function call
* better semantics . Async and await are more semantically compared to * and yield
* wider applicability . CO Module Convention, the yield command can only be followed by a Thunk function or Promise object. The await command for the async function can then be Promise or a value of the original type (Number,string,boolean, but this is equivalent to a synchronous operation)
* The return value is Promise. The Async function return value is a Promise object that is more convenient than the iterator object returned by the generator function and can be invoked directly using the then () method Async compared to other asynchronous operations
First, define a fetch method to obtain information for GitHub User:
function Fetchuser () {return
new Promise (Resolve, Reject) => {
fetch (' https://api.github.com/users/ Superman66 ')
. Then ((data) => {
Resolve (Data.json ());
}, (Error) => {
reject (Error)}
)
});
}
Promise Way
/**
* Promise mode
/
function getuserbypromise () {
fetchuser ()
. Then ((data) => {
Console.log (data);
}, (Error) => {
console.log (Error)}
)
}
Getuserbypromise ();
Promise's approach solves the callback hell, but this way is filled with the Promise then () method, and if the process is complex, the entire code will be filled with then. Semantics is not obvious, the code flow is not a good representation of the execution process.
Generator Way
/**
* Generator mode * *
function* fetchuserbygenerator () {
Const user = yield Fetchuser ();
return user;
}
Const G = Fetchuserbygenerator ();
Const result = G.next (). value;
Result.then ((v) => {
console.log (v);
}, (Error) => {
console.log (error);
})
Generator way solves some problems of Promise, the process is more intuitive and semantic. But the problem with generator is that the execution of the function relies on the executor, which needs to be executed by G.next () each time.
Async Way
/**
* Async Mode * *
async function Getuserbyasync () {Let
user = await fetchuser ();
return user;
}
Getuserbyasync ()
. Then (v => console.log (v));
The Async function solves the problem of the above two ways perfectly. The process is clear, intuitive and semantically obvious. Manipulating an asynchronous process is like manipulating the synchronization process. At the same time, the Async function has its own executor, which does not need to be loaded manually. Grammar
The async function returns a Promise object
The value returned by the Async function internal return. becomes the parameter of the then method callback function.
Async function F () {return
' Hello World '
};
F (). Then ((v) => Console.log (v))//Hello World
If an exception is thrown inside the async function, it causes the returned Promise object state to become a reject state. The error thrown is received by the Catch method callback function.
Async function E () {
throw new error (' Error ');
}
E (). Then (v => console.log (v))
. catch (E => console.log (e));
the Promise object returned by the Async function must wait until the Promise object of all the internal await commands has been executed before a state change occurs
That is, the callback for the then method is executed only if the asynchronous operation inside the async function has finished executing.
Const DELAY = Timeout => new Promise (resolve=> settimeout (resolve));
Async function f () {
await delay (1000);
await delay ();
Await delay (3000);
Return to ' done ';
}
F (). Then (v => console.log (v)); Wait for 6s before outputting ' done '
under normal circumstances, the await command followed by Promise, if not, will be converted to an immediate resolve Promise
As the following example:
Async function F () {return
await 1
};
F (). Then ((v) => Console.log (v))//1
If the state of the reject is returned, it is caught by the catch method. error handling of Async function
The syntax of the async function is not difficult and difficult to deal with in error.
Let's take a look at the following example:
let A;
Async function f () {
await promise.reject (' error ');
A = await 1; This section of await does not perform
}
f (). Then (v => console.log (a));
As shown above, when a reject state is present in the Async function, the await behind is not executed.
workaround : You can add Try/catch.
The correct wording let
A;
Async function correct () {
try {
await promise.reject (' ERROR ')
} catch (Error) {
Console.log (Error );
}
A = await 1;
return A;
}
Correct (). Then (v => console.log (a)); 1
If you have more than one await, you can put it all in Try/catch. How to use in a project
is still used through Babel.
You only need to set presets as stage-3.
Installation dependencies:
NPM Install babel-preset-es2015 babel-preset-stage-3 babel-runtime babel-plugin-transform-runtime
Modify. BABELRC:
"Presets": ["es2015", "stage-3"],
"plugins": ["Transform-runtime"]
This allows you to use the Async function in your project. further Reading Understanding JavaScript ' s async await async/await-best practices in asynchronous programming asynchronous operations and Async functions
Article Starting in my blog: chenhuichao.com