让express支持async/await、promise

2017-3-20    分类: nodejs笔记

node.js低版本不支持async/await、promise语句在express框架开发中需要支持就必须安装各种兼容模块才能跑起来。

编辑package.json:

"dependencies": {
  "babel-core": "^6.18.2",
  "babel-preset-es2015": "^6.18.0",
  "babel-preset-stage-3": "^6.17.0",
  "babel-runtime": "^6.18.0",
  "bluebird": "^3.4.6",
  "express": "^4.14.0"
 },
 "devDependencies": {
  "babel-plugin-transform-runtime": "^6.15.0"
 }

添加完成后记得安装npm install

 

创建脚本.babelrc

{
  "presets": [
      "stage-3",
      "es2015"
  ],
  "plugins": [
     [
       "transform-runtime",
       {
         "polyfill": false,
         "regenerator": true
       }
     ]
   ]
}

 

在需要支持promise的路由处引入以下代码即可

const Promise = require('bluebird');

 

express启动文件默认在./bin/www,现在添加文件start.js内容如下:

require('babel-core/register');
require('./www');
require("babel-core").transform("code", {
  plugins: ["transform-runtime"]
});

 

以后启动express时就执行:

node ./bin/start.js

这样尝试着用async/await、promise语法编程看看是否成功执行

相关文件下载:express-babel-master