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

标签 node.js async-await

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

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

我的代码是:

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/

相关文章:

javascript - 异步 NPM 模块不为数组中的每个项目执行 setTimeout

c# - 从 Windows 服务调用异步方法

c# - 异步和等待 - 控制台、Windows 窗体和 ASP.NET 之间的区别

javascript - JS异步/等待任务队列

node.js - Flash 策略文件请求

javascript - 如何将数据从 Angular 服务发布到 Node ?

javascript - 在使用 ES6 类和生成器函数时,如何避免使用 `self = this` hack?

react-native - 异步/等待函数返回 _40 : 0, _65 : 0, _55 : null, _72: null

.net - 不需要取消的异步方法

node.js - 如何为electron.js构建React文件