gpt4 book ai didi

javascript - async 和await 函数先于其他函数运行

转载 作者:行者123 更新时间:2023-12-03 00:15:36 24 4
gpt4 key购买 nike

我的processawait函数不等待preProccess结束:

我有一个调用 Controller 的路由类

exports.Controller = async function (req, res) {

let callbackPreProccess = await Implementation.preProccess(payload, resolve);

let callbackProccess = await Implementation.proccess(callbackPreProccess, resolve);
res.status(200).json(callbackProccess);

//

export class Implementation{

preProccess(payload: any, resolve: string): Promise<any> {
return new Promise(async (resolve, reject) => {
try {
if (payload.test == true){
logger.info('preProccess OK');
}

//preProccess connect to the DB and get some informations,
//enrich the payload and return
logger.info('preProccess DB access OK');

resolve(payload);

}
catch(error){
throw new Error("Manual Error");
reject(error);
}
};


proccess(payload: any, resolve: string): Promise<any> {
return new Promise(async (resolve, reject) => {
try {
logger.info('proccess OK');

resolve(true);
}
catch(error){
reject(error);
}
};
}

我所期望的所有等待函数是怎样的:

info&& 'preProccess OK'
info&& 'preProccess DB access OK'
info&& 'proccess OK'

但是回到我身边:

info&& 'preProccess OK'
info&& 'proccess OK'
info&& 'preProccess DB access OK'

即使我强制抛出错误,期望不运行该过程,它们也会运行

info&& 'preProccess OK'
info&& 'proccess OK'
error&& 'Manual error'

但是当我在 process Controller 上使用 .then 并手动等待 preProccess 时,它工作得很好。

最佳答案

创建新进程时使用await。

 return await new Promise(async (resolve, reject) => {

关于javascript - async 和await 函数先于其他函数运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54535086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com