最新版本的 node.js 支持 ES7nodejs async使用方法/await 吗?怎么开启

posted in,
Let’s take a code snippet that contains the demonstration of async/await —
– our objective is to transpile this piece of code to ES5 (current day Javascript) so we can run it with today’s version of NodeJS.
You will notice a command on top of the snippet which no longer works because Babel JS has changed. I am going to describe how we can do it with the latest version of babel as of this writing (6.1.4 (babel-core 6.1.4)).
Install Babel and Plugins
The new Babel depends on individual plugins to transform and parse codes. To transform async functions, we shall use the transform-regenerator plugin. We also need to add the syntax plugin to recognize the async/await syntax. Otherwise Babel won’t recognize those. Apart from that, we also install the ES2015 preset which includes a sane set of plugins for transforming ES6 to ES5. We will keep those so we can use other ES6 goodies.
First we install babel-cli globally:
npm install -g babel-cli
npm install -g babel-cli
Here’s our package.json file so you can just do npm install:
JavaScript
"name": "awesome-async",
"version": "1.0.0",
"description": "",
"main": "github.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"author": "",
"license": "ISC",
"dependencies": {
"babel-plugin-syntax-async-functions": "^6.1.4",
"babel-plugin-transform-regenerator": "^6.1.4",
"babel-polyfill": "^6.1.4",
"babel-preset-es2015": "^6.1.4",
"request": "^2.65.0"
123456789101112131415161718
{&&"name": "awesome-async",&&"version": "1.0.0",&&"description": "",&&"main": "github.js",&&"scripts": {&&&&"test": "echo \"Error: no test specified\" && exit 1"&&},&&"author": "",&&"license": "ISC",&&"dependencies": {&&&&"babel-plugin-syntax-async-functions": "^6.1.4",&&&&"babel-plugin-transform-regenerator": "^6.1.4",&&&&"babel-polyfill": "^6.1.4",&&&&"babel-preset-es2015": "^6.1.4",&&&&"request": "^2.65.0"&&}}
Configuring Babel
Here’s the .babelrc file I put in the same directory:
JavaScript
"presets": ["es2015"],
"plugins": ["syntax-async-functions","transform-regenerator"]
{&&"presets": ["es2015"],&&"plugins": ["syntax-async-functions","transform-regenerator"]}
The file tells babel how to transform your code.
Transpile & Run
Once we have installed the dependencies, we can then start transpiling the codes to JS:
babel github.es6 -o github.js
node github.js
babel github.es6 -o github.jsnode github.js
You might run into a problem like this:
/Users/masnun/Projects/awesome-async/github.js:34
return regeneratorRuntime.async(function printPublicGists$(_context) {
ReferenceError: regeneratorRuntime is not defined
at printPublicGists (/Users/masnun/Projects/node/github.js:34:10)
at Object.&anonymous& (/Users/masnun/Projects/node/github.js:63:1)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
12345678910111213
/Users/masnun/Projects/awesome-async/github.js:34&&return regeneratorRuntime.async(function printPublicGists$(_context) {&&&&&&&& ^ReferenceError: regeneratorRuntime is not defined&&&&at printPublicGists (/Users/masnun/Projects/node/github.js:34:10)&&&&at Object.&anonymous& (/Users/masnun/Projects/node/github.js:63:1)&&&&at Module._compile (module.js:460:26)&&&&at Object.Module._extensions..js (module.js:478:10)&&&&at Module.load (module.js:355:32)&&&&at Function.Module._load (module.js:310:12)&&&&at Function.Module.runMain (module.js:501:10)&&&&at startup (node.js:129:16)&&&&at node.js:814:3
It’s because we need to include the regenerator run time. The runtime is packed in the babel-polyfill we have already installed. We just need to include it in our source code. So the final github.es6 file would look like this:
JavaScript
require("babel-polyfill");
import request from "request";
// promise returning function
function get (url){
return new Promise(function(resolve, reject){
method: 'GET',
json: true,
headers: {
'User-Agent': 'request'
}, function(err, resp, body){
reject(err);
resolve(body);
// create a new "async" function so we can use the "await" keyword
async function printPublicGists(){
// "await" resolution or rejection of the promise
// use try/catch for error handling
var gists = await get('/gists/public');
// now you can write this like syncronous code!
gists.forEach(function(gist){
console.log(gist.description);
} catch (e) {
// promise was rejected and we can handle errors with try/catch!
printPublicGists();
12345678910111213141516171819202122232425262728293031323334353637383940414243
require("babel-polyfill");&import request from "request";&// promise returning functionfunction get (url){&&return new Promise(function(resolve, reject){&&&&request({&&&&&&method: 'GET',&&&&&&url: url,&&&&&&json: true,&&&&&&headers: {&&&&&&&&'User-Agent': 'request'&&&&&&}&&&&}, function(err, resp, body){&&&&&&if(err){&&&&&&&&reject(err);&&&&&&} else {&&&&&&&&resolve(body);&&&&&&}&&&&});&&});}&&// create a new "async" function so we can use the "await" keywordasync function printPublicGists(){&&// "await" resolution or rejection of the promise&&// use try/catch for error handling&&try {&&&&var gists = await get('/gists/public');&&&&&&&&// now you can write this like syncronous code!&&&&gists.forEach(function(gist){&&&&&&console.log(gist.description);&&&&});&&} catch (e) {&&&&// promise was rejected and we can handle errors with try/catch!&&}}&&printPublicGists();
Now if we transpile and run again, it should work fine.
ABOUT THE AUTHOR
Insert/edit link
Enter the destination URL
Open link in a new tab
Or link to existing content
No search term specified. Showing recent items.
Search or use up and down arrow keys to select an item.async/await成对匹配,不是一个死循环吗?
async/await成对匹配,不是一个死循环吗?
要在async修饰的方法体里面使用await,被await的方法需要用async修饰、而且里面必须要有await。
这样一层一层递推下去,最后似乎必须await到一个内置的耗时方法上去,否则就没法结束。这究竟是怎么回事???
麻烦熟悉的师兄师姐们指点迷津。
举例(简化):
async void DoWork1()
await DoWork11();
async Task DoWork11()
await DoWork111();
async Task DoWork111() //不用 async修饰就会提示“并非所有的代码路径都返回值”
await DoWork1111();
//如果方法用async修饰而此处不用await修饰就会提示“此异步方法缺少await运算符,将同步运行”,而且好多方法不能await,彻底晕了...
async void foo()
int x = await MyAsync(1, 2);
Console.WriteLine(x);
void bar()
var aw = MyAsync(1, 2).GetAwaiter();
aw.OnCompleted(() =& { Console.WriteLine(aw.GetResult()); });
Task&int& MyAsync(int x, int y)
return new Task&int&(() =& x + y);
解决方案二:
async Task DoWork111()
不用async也可以,注意,返回的是Task。
await/async只是语法糖。
解决方案三:
比如如上代码,你可以看到,你完全可以不用async/await
async Task&int& MyAsync(int x, int y)
return x +
这些都是等价的。
解决方案四:
Task&int& MyAsync(int x, int y)
var tf = new TaskFactory&int&();
return tf.StartNew(() =& x + y);
解决方案五:
await就是等待async的异步返回。不然你不处理返回也可以啊。
解决方案六:
async修饰方法必须用await,很奇怪的规定,你说的是Java吗?
如果是,绝对不是必须,而是有需求才用。}

我要回帖

更多关于 nodejs 安装 async 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信