如何使用async await作为模块方法

时间:2016-10-03 08:55:50

标签: javascript node.js express asynchronous babeljs

这是我使用Express

编写的路线
const express=require('express');
const router=express.Router();

const trackRepo=require('../model/track');

router.post('/live',function(req,res){
    const time=1439832167;
    const list=trackRepo.getAlerts(time);
    res.json({list:list});
});

module.exports=router;

我使用async / await:

const r=require('rethinkdb');
const config=require('../config/rethinkdb');

r.connect(config).then((conn)=>{
    module.exports.getAlerts=async (function(time){
        const cursor=await r.table('track').filter({createdAt:time}).run(conn);
        return await cursor.toArray();
    });
});

这是我的app.js

const express=require('express');
const app=express();
const server=require('http').createServer(app);
const bodyParser=require('body-parser');
const cookieParser=require('cookie-parser');
const session=require('express-session');

// Utilities
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(cookieParser());

// Template
app.set('view engine','ejs');

// Static
app.use(express.static(__dirname+'/static'));

// Middlewares
app.use(require('./route/web'));
app.use(require('./route/track'));

// Listening
app.listen(4444,function(){
    console.log('Server listening on port 4444...');
});

我写了一个名为server.js的文件,这应该是入口点,在运行服务器之前将app.js转换为babel

require('babel/register');
require('./app.js');

这是我在package.json

中安装的devDependencies列表
 "devDependencies": {
    "babel-cli": "^6.16.0",
    "babel-core": "^6.17.0",
    "babel-plugin-syntax-async-functions": "^6.13.0",
    "babel-plugin-transform-async-to-generator": "^6.16.0",
    "babel-plugin-transform-regenerator": "^6.16.1",
    "babel-polyfill": "^6.16.0",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-latest": "^6.16.0"
  }

当我使用命令babel-node server.js启动服务器时,它会在异步等待行中抛出Unexpected token。我按照我搜索的指南并感到困惑,我不明白为什么它一直在抛出错误。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

由于语法错误async(function(){ await … }),您调用了一个名为async的函数,函数表达式作为参数,使用{{1}的函数表达式}关键字尽管被标记为await

应该是

async

router.post('/live', async function(req,res){
    const time = 1439832167;
    const list = await trackRepo.getAlerts(time);
//               ^^^^^ it's a promise, so you need to await it
    res.json({list:list});
});