Async/await uses synchronous methods to write asynchronous code, reducing the difficulty of asynchronous calls to close to 0, and the future will shine. At the moment, however,async/await is still in ES7 's draft because of the standardized caching pace . In order to taste first, the following two methods are tested:
- use the community-provided asyncawait package
- Use Draft ES7
using community-providedAsyncawaitModuleGitAddress
[email protected]: Yortus/asyncawait.git
How to use:
1. installing the node module
a) npm install [email protected] –save
2. To create a sample class Asyncservice.js
varAsync= require(' Asyncawait/async ');
varawait= require(' asyncawait/await ');
varSleep= Async(
functionSleep(timeout) {
return newPromise(function(Resolve, Reject) {
SetTimeout(function() {
Resolve ();
}, timeout);
});
}
);
(Async(
function() {
Console.Log(' Do some thing, '+ NewDate ());
await(Sleep( the));
Console.Log(' Do other things, '+ NewDate ());
}
))();
3. Run Asyncservice.js
a) Node asyncservice.js
b) operation Result:
Do some thing, Wed June 11:09:05 gmt+0800 ( China Standard Time )
Do other things, Wed June 11:09:08 gmt+0800 ( China Standard Time )
Precautions
1. the asyncawait module internally references the Bluebird module .
2. no need to compile to Es5, can be run directly .
UseES7Draft How to use:
1. To install the node module, a series of modules are required:
a) babel-cli
b) babel-preset-es2015 "
c) babel-preset-react ":
d) babel-preset-stage-3
e) babel-polyfill
2. To create a sample class Asyncawaitservice.js
Async FunctionSleep(timeout) {
return newPromise(Resolve, reject) = {
SetTimeout(function() {
Resolve ();
}, timeout);
});
}
(Async Function() {
Console.Log(' Do some thing, '+ NewDate ());
awaitSleep( the);
Console.Log(' Do other things, '+ NewDate ());
})();
3. compiling Asyncawaitservice.js
a) Configure Babel
I. Add the Babel node to the Package.json as follows:/ c6>
"Babel" " presets " : [
"es2015" "react" " stage-3 "
],
"plugins" : []
}
b) compiling
Babel Asyncawaitservice.js--out-file Asyncawaitservice_es5.js
Or
Babel Asyncawaitservice.js-o Asyncawaitservice_es5.js
c) to mark compiled code
in the Asyncawaitservice_es5.js the script header adds the following code:
require (' Babel-polyfill ')
4. Run Asyncawaitservice_es5.js
a) Node asyncawaitservice_es5.js
b) operation Result:
Do some thing, Wed June 11:54:13 gmt+0800 ( China Standard Time )
Do other things, Wed June 11:54:16 gmt+0800 ( China Standard Time )
Precautions
1. async/awaitcan be run directly by compiling it to Es5 via Babel.
2. Babel compilation related content can refer to Ruan Yi Feng blog http://www.ruanyifeng.com/blog/2016/01/babel.html
Nodejs using Asyncawait two methods