Passing in Async functions to Node.js Express.js router

前端 未结 5 2098
别跟我提以往
别跟我提以往 2021-02-04 05:37

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

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

Example:

<         


        
5条回答
  •  旧巷少年郎
    2021-02-04 06:24

    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"))
    

    And voila

    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
    

    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.

提交回复
热议问题