gpt4 book ai didi

node.js - Nodejs : How to avoid async call in nodejs inside loop?

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:06 25 4
gpt4 key购买 nike

这里我需要从数据库中获取数据两次并将结果作为响应返回。

但我的问题是在从数据库获取数据之前调用响应函数,它将返回空响应

我的代码是:

Stages.findById(comp.currentStage.stage, function(stgErr, stageName) {

if (stgErr) {
res.json(HttpStatus.INTERNAL_SERVER_ERROR, usrErr);
return;
}

comp.currentStageName = stageName.name;
components.push(comp);

ServiceProviderUser.findById(comp.currentStage.user, function(
usrErr,
userName
) {
if (usrErr) {
res.json(HttpStatus.INTERNAL_SERVER_ERROR, usrErr);
return;
}
comp.personResponsible = userName.firstName + " " + userName.lastName;
components.push(comp);
console.log("1111111111", comp);
});

checkCondition(); //check condition is the function for response send
});

function checkCondition() {
res.json(HttpStatus.OK, components);
}

最佳答案

只需将返回函数调用移动到发送数据库调用的回调中即可

Stages.findById(comp.currentStage.stage, function (stgErr, stageName){
if (stgErr) {
res.json(HttpStatus.INTERNAL_SERVER_ERROR, usrErr);
return;
}
comp.currentStageName = stageName.name;
components.push(comp);
ServiceProviderUser.findById(comp.currentStage.user, function (usrErr, userName){
if (usrErr) {
res.json(HttpStatus.INTERNAL_SERVER_ERROR, usrErr);
return;
}
comp.personResponsible = userName.firstName+ ' '+userName.lastName;
components.push(comp);
console.log("1111111111",comp);

checkCondition() //moved in callback of this DB call
})

})

function checkCondition() {
res.json(HttpStatus.OK, components);
}

但这不是一个好方法。您可以使用“Promises”来更好地处理异步代码。我发现this作为对 promise 的最好解释。希望能帮助到你 !!

关于node.js - Nodejs : How to avoid async call in nodejs inside loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51035597/

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