private runMiddlewares(route: Route | ExceptionRoute, request: HttpRequest, response: HttpResponse): Promise<any> {
return new Promise((resolve, reject) => {
try {
route.middlewares.forEach(async (middleware: IMiddleware) => {
console.log('begin run middleware');
await middleware.process(request, response);
console.log('resolve run middleware');
console.log(request.body);
});
console.log('resolve all runMiddlewares');
resolve();
} catch (e) {
reject(e);
}
});
}
我写了这个函数runMiddlewares
,当所有middleware.process()
都已解决时,理想情况下应该解析()。我正在使用typescript await
功能,但它似乎没有工作。我期待这样的事情发生在route.middlewares.forEach(
内部
这继续在forEach
循环中的所有中间件,当列表全部完成然后只有'解决所有runMiddlewares'应该打印,最后,private runMiddlewares( ... )
应该解决。
但相反,forEach
现在正在立即解决,从而阻止所有中间件甚至完成。
应如何处理?我认为await
将在forEach
循环中处理它,然后才会调用resolve
的runMiddlewares
。我在这里错过了什么?
您可以使用map
从中间件创建一系列承诺。这一系列的承诺可以交给Promise.all
,当数组的每个承诺都得到解决时,它会解决。
await Promise.all(route.middlewares.map((middleware: IMiddleware) => {
console.log('begin run middleware');
const promise = middleware.process(request, response);
console.log('resolve run middleware');
console.log(request.body);
return promise
});
或者更紧凑:
runMiddlewares(...) {
return Promise.all(
route.middlewares.map((middleware: IMiddleware) => {
return middleware.process(request, response))
})
)
}
所以,按照建议(https://cn.eslint.org/docs/3.0.0/rules/no-await-in-loop),我写了如下
private runMiddlewares(route: Route | ExceptionRoute, request: HttpRequest, response: HttpResponse): Promise<any> {
return new Promise(async (resolve, reject) => {
try {
const middlewarePromiseArry: any[] = [];
route.middlewares.forEach((middleware: IMiddleware) => {
console.log('begin run middleware');
middlewarePromiseArry.push(middleware.process(request, response));
// removed the use of await inside of forEach loop following this link: https://cn.eslint.org/docs/3.0.0/rules/no-await-in-loop
// await middleware.process(request, response);
// console.log('resolve run middleware');
// console.log(request.body);
});
await Promise.all(middlewarePromiseArry);
console.log('resolve all runMiddlewares');
resolve();
} catch (e) {
reject(e);
}
});
}
我很高兴接受进一步的答案和建议/改进:)