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

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

问题描述

这看起来像一个简单的谷歌,但我似乎无法找到答案......

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/awaitES7 不是 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.

您的代码将在 node.js 中运行.我已经测试了以下代码

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在它的代码中的一个promise.这在 node 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天全站免登陆