Node.js/Express:中间件中的异步函数?
Node.js/Express: async function inside middleware?
我想知道您如何让异步函数在 中间件 中工作?通常在函数前面 await
可以完成工作,但在 middleware 中似乎不起作用。
index.js:
const bob= require('../middleware/bob');
router.get('/', [bob(['channel1','channel2','channel3'])], async (req, res) => {
console.log('3')
})
middleware/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
await
等待承诺。从 test
函数返回的承诺会立即得到解决。 async
函数不应该知道 setTimeout
它内部发生的任何异步进程,除了与 await
或 return
.
链接的承诺
如果是为了拖延时间,应该是:
async function test(){
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('1')
}
我想知道您如何让异步函数在 中间件 中工作?通常在函数前面 await
可以完成工作,但在 middleware 中似乎不起作用。
index.js:
const bob= require('../middleware/bob');
router.get('/', [bob(['channel1','channel2','channel3'])], async (req, res) => {
console.log('3')
})
middleware/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
await
等待承诺。从 test
函数返回的承诺会立即得到解决。 async
函数不应该知道 setTimeout
它内部发生的任何异步进程,除了与 await
或 return
.
如果是为了拖延时间,应该是:
async function test(){
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('1')
}