【问题标题】:Node.js/Express: async function inside middleware?Node.js/Express:中间件中的异步函数?
【发布时间】:2018-10-07 14:45:20
【问题描述】:

我想知道您如何使异步函数在中间件中工作?通常函数前面的await 可以完成工作,但在中间件中它似乎不起作用。

index.js:

const bob= require('../middleware/bob');
router.get('/', [bob(['channel1','channel2','channel3'])], async (req, res) => {
    console.log('3')
})

中间件/bob.js:

async function test(){
    setTimeout(() => {
        console.log('1')
    }, 2000);
}

module.exports = function(channels){
   return async(req, res, next) =>{
        await test();
        console.log('2')

        next();
    }
}

当我运行这段代码时。它将写入控制台:2 3 1

【问题讨论】:

    标签: node.js express middleware


    【解决方案1】:

    await 等待承诺。从test 函数返回的承诺会立即解决。 async 函数不应该知道 setTimeout 内部发生的任何异步进程,除了与 awaitreturn 链接的承诺。

    如果打算推迟,应该是:

    async function test(){
        await new Promise(resolve => setTimeout(resolve, 2000));
        console.log('1')
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-02
      • 2017-02-04
      • 2019-07-04
      • 2019-01-20
      • 2018-10-23
      • 2020-01-24
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      相关资源
      最近更新 更多