将异步功能传递给Node.js Express.js路由器 [英] Passing in Async functions to Node.js Express.js router

查看:118
本文介绍了将异步功能传递给Node.js Express.js路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个简单的Google,但我似乎找不到答案...

This seems like a straightforward google, but I can't seem to find the answer...

您可以将ES7异步功能传递给Express路由器吗?

Can you pass in ES7 async functions to the Express router?

示例:

var express = require('express');
var app = express();

app.get('/', async function(req, res){
  // some await stuff
  res.send('hello world');
});

如果没有,您能为我指出正确处理ES7样式问题的正确方向吗?还是我只需要使用诺言?

If not, can you point me in the right direction on how to handle this problem ES7 style? Or do I just have to use promises?

谢谢!

推荐答案

可能是因为async/await ES7 而不是ES6功能,所以未找到结果,它在节点> =中可用7.6.

May be you didn't found results because async/await is an ES7 not ES6 feature, it is available in node >= 7.6.

您的代码将在节点中工作. 我已经测试了以下代码

Your code will work in node. I have tested the following code

var express = require('express');
var app = express();

async function wait (ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms)
  });
}

app.get('/', async function(req, res){
  console.log('before wait', new Date());
  await wait(5 * 1000);
  console.log('after wait', new Date())
  res.send('hello world');
});

app.listen(3000, err => console.log(err ? "Error listening" : "Listening"))

还有瞧

MacJamal:messialltimegoals dev$ node test.js 
Listening undefined
before wait 2017-06-28T22:32:34.829Z
after wait 2017-06-28T22:32:39.852Z
^C

基本上,您必须async一个函数才能在其代码中的承诺上使用await. LTS v6节点不支持此功能,因此可以使用babel来转译代码. 希望这会有所帮助.

Basicaly you got it, you have to async a function in order to await on a promise inside its code. This is not supported in node LTS v6, so may be use babel to transpile code. Hope this helps.

这篇关于将异步功能传递给Node.js Express.js路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆