如何在javascript中包装来自异步调用的所有结果?

时间:2017-11-04 15:58:50

标签: javascript angularjs node.js mongodb express

我有三个模型,我想从mongodb文档中搜索结果,并返回性别,种族和年龄的信息。但是find方法是异步的。那我该怎么办?

Sex.find(function(err, sexModels) {
        if(err)
            alert('cannot find sex information');
        if(sexModels) {
            info.sex = sexModels;
        }
    });
    Race.find(function(err, raceModels) {
        if (err)
            alert('cannot find race information');
        if (raceModels) {
            info.race = raceModels;
        }
    });
    Age.find(function(err, ageModels) {
        if(err)
            alert('cannot find age information');
        if(ageModels) {
            info.age = ageModels;
        }
    });
    res.send(info); // this would be void coz find is asynchronous

2 个答案:

答案 0 :(得分:0)

没有承诺简单嵌套:

 Sex.find({},function(err, sexModels) {
            if(err)
                alert('cannot find sex information');
            if(sexModels) {
                info.sex = sexModels;
                Race.find({},function(err, raceModels) {
                   if (err)
                      alert('cannot find race information');
                   if (raceModels) {
                      info.race = raceModels;
                      Age.find({},function(err, ageModels) {
                            if(err)
                                alert('cannot find age information');
                            if(ageModels) {
                                info.age = ageModels;
                                res.send(info); // here
                            }
                        });
                    }
                });
            }
    });

答案 1 :(得分:0)

您可以创建一个中间方法,检查info上是否存在所有属性

Sex.find(function(err, sexModels) {
    if(err)
        alert('cannot find sex information');
    if(sexModels) {
        info.sex = sexModels;
        checkAndSendResponse(info);
    }
});
Race.find(function(err, raceModels) {
    if (err)
        alert('cannot find race information');
    if (raceModels) {
        info.race = raceModels;
        checkAndSendResponse(info);
    }
});
Age.find(function(err, ageModels) {
    if(err)
        alert('cannot find age information');
    if(ageModels) {
        info.age = ageModels;
        checkAndSendResponse(info);
    }
});

function checkAndSendResponse(p_info) {
  if(p_info.age && p_info.sex && p_info.race) {
    res.send(info);
  }
}