使用async/await——Nodejs+ExpressJs+Babel

來源:互聯網
上載者:User

標籤:main   sgu   expr   type   href   des   name   ddr   github   

在使用諸如restify/expressjs等Nodejs Web Framework時,我們最頭疼的問題就是回調黑洞。

雖然後又Koa/Koa2號稱“The Next Framework”使用co解決問題,但是核心this的設計和各種小流middleware對req/res的隨意濫用,導致我對這個架構失去好感。

Expressjs依然是我在使用Nodejs編寫API和Web時的首選架構。

在使用Expressjs時,如果我們也想使用await/async這些在ES7 stage-3中的特性,就需要藉助別的工具。目前我推薦的是typescript(時下版本2.0.10)和babel,本章只介紹使用babel的方法,如有同學與我一樣同樣對ts興趣甚深,可私信或留言彼此學習進步。

第一步

我們仍然使用npm init來產生一個package,內容如下:

 1 { 2   "name": "express_babel_demo2", 3   "version": "1.0.0", 4   "description": "", 5   "main": "index.js", 6   "scripts": { 7     "test": "echo \"Error: no test specified\" && exit 1" 8   }, 9   "author": "",10   "license": "ISC",11   "dependencies": {12     "babel-core": "^6.18.2",13     "babel-preset-es2015": "^6.18.0",14     "babel-preset-stage-3": "^6.17.0",15     "babel-runtime": "^6.18.0",16     "bluebird": "^3.4.6",17     "express": "^4.14.0"18   },19   "devDependencies": {20     "babel-plugin-transform-runtime": "^6.15.0"21   }22 }

可以看到,在我們的依賴中,已經存在babel-core等組件,bluebird是我最喜歡的一個Promise A+實現,效能也是真男人。

第二步

然後我們建立一個.babelrc,用來描述babel的配置:

 1 { 2     "presets": [ 3         "stage-3", 4         "es2015" 5     ], 6     "plugins": [ 7         [ 8             "transform-runtime", 9             {10                 "polyfill": false,11                 "regenerator": true12             }13         ]14     ]15 }

我們使用babel官方推薦的transform-runtime來進行啟動翻譯工作,而不是pollify,雖然後者有更多的功能,但是對於不需要的人來說,那是對原生對象的汙染和項目效能的負擔。

第三步

建立一個index.js檔案,這個是demo的開機檔案,代碼依舊簡單,引入babel、babel翻譯和expressjs的入口:

1 require(‘babel-core/register‘);2 require(‘./app.js‘);3 require("babel-core").transform("code", {4     plugins: ["transform-runtime"]5 });

第四步

編寫一個app.js,使用原生fs庫非同步讀取一下package.json檔案並輸出:

 1 var express = require(‘express‘); 2 var app = express(); 3 var fs = require(‘fs‘); 4 var Promise = require(‘bluebird‘); 5  6 app.get(‘/‘, function (req, res) { 7     testAsync(); 8     res.send(‘Hello World!‘); 9 });10 11 var server = app.listen(3000, function () {12     var host = server.address().address;13     var port = server.address().port;14 15     console.log(‘Example app listening at http://%s:%s‘, host, port);16 });17 18 19 20 async function testAsync(name) {21     console.log("hello");22     for (let i = 0; i < 3; i++) {23         let fileContent = await readFile("package.json");24         console.log(new Buffer(fileContent).toString());25         console.log(".");26     }27     console.log(name);28 }29 let readFile = Promise.promisify(fs.readFile);

然後執行一下npm install,會下載依賴

再node index.js啟動我們所編寫的express demo。

瀏覽器訪問localhost:3000,在控台裡就能看到“非同步讀取、同步輸出”的內容了。

demo github地址:GitHub Demo

 

使用async/await——Nodejs+ExpressJs+Babel

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.