gpt4 book ai didi

javascript - Node.js + 异步系列执行

转载 作者:行者123 更新时间:2023-12-02 17:32:17 25 4
gpt4 key购买 nike

在我的 Node 应用程序中,我使用 async.series 来执行 3 个查询,它执行得很好。但是在我的第三个查询执行中,我必须根据第三个查询的结果执行另一个查询,它也工作得很好。但是我在第三个查询中执行一些逻辑,所以在所有完成之后我只需要调用回调......

我的代码:

async.series({
levels: function(cb) {
sequelize.query("select country_id, country_name, level0, level1, level2, level3, level4 from levels").success(function(levelsResults) {
levelsResult = levelsResults;
cb(null, levelsResult);
})
},
level1: function(cb) {
sequelize.query("select id_0, name_0, name_1 from xxxxx group by id_0, name_0, name_1").success(function(level1Result) {
level1result = level1Result;
cb(null, level1result);
})
},
keys: function(cb) {
sequelize.query("select id_0 from xxxx group by id_0").success(function(id_0Result) {
var obj = {};
for (var i = 0; i < id_0Result.length; i++) {
sequelize.query("select id_0, value->>'yyyy' as value from xxxx where id_0 = " + id_0Result[i].id_0 + " limit 1").success(function(keyResult) {
var keyArray = [];
var keysObjectArray = [];
id_0 = keyResult[0].id_0;
keyResult = keyResult[0].value;
keyResult = JSON.parse(keyResult);

for (var prop in keyResult) {
keyArray.push(prop)
}
obj["" + id_0 + ""] = keyArray;
keysObjectArray.push(obj);
cb(null, keysObjectArray);
---.my problem is here cb is called in the 1st iteration of
for loop.It should be called after loop finishes

})
}
})
}
}, function seriesFinal(seriesErr, seriesResults) {
if (seriesErr) throw new Error("Something bad!");
onSuccess(JSON.stringify(seriesResults), callback);

});

我的结果是:

{"levels":[{levsls}],"level1":[{level1}],"keys":[{}]};

但我期待的是:

{"levels":[{levsls}],"level1":[{level1}],"keys":[{},{}]};

编辑:

简单地说,我怎样才能使 sequlize 查询执行 for 循环,最后必须调用回调

帮我解决这个问题..提前致谢......

最佳答案

“for”循环运行“n”个查询,随机回调“success”函数。

您可以使用计数器来确保回调所有查询

sequelize.query("select id_0 from xxxx group by id_0").success(function(id_0Result){
var obj = {};
var counter = 0;
for(var i=0; i<id_0Result.length; i++){
sequelize.query("select id_0, value->>'yyyy' as value from xxxx where id_0 = "+id_0Result[i].id_0+" limit 1").success(function(keyResult){
var keyArray=[];
var keysObjectArray =[];
id_0 = keyResult[0].id_0;
keyResult = keyResult[0].value;
keyResult = JSON.parse(keyResult);

for (var prop in keyResult){
keyArray.push(prop)
}
obj[""+id_0+""] = keyArray;
keysObjectArray.push(obj);
counter +=1;
if(counter === id_0Result.length )
{
cb(null, keysObjectArray);
}

})
}

请注意,keysObjectArray 中的顺序是随机的,回调也是随机的。

希望有帮助。

约安

关于javascript - Node.js + 异步系列执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22952907/

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