use*_*497 4 middleware node.js express
我想知道如何使异步函数在中间件中工作?通常await在函数前面会完成工作,但在中间件中似乎无法正常工作.
index.js:
const bob= require('../middleware/bob');
router.get('/', [bob(['channel1','channel2','channel3'])], async (req, res) => {
console.log('3')
})
Run Code Online (Sandbox Code Playgroud)
中间件/ 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();
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时.它将写入控制台:2 3 1
await等待承诺.从test函数返回的promise将立即解决.async函数不应该知道setTimeout它内部发生的任何异步进程,除了与await或链接的promises return.
如果打算延迟它,它应该是:
async function test(){
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('1')
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
350 次 |
| 最近记录: |