gpt4 book ai didi

node.js - 使用nodejs、async、falls、each和mysql同步控制流

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

我在使用 mysql 异步时遇到一些控制流问题,希望得到一些帮助/建议。基本上,我有一系列元素。我想遍历数组,并针对每个项目检查它是否存在于 MySQL 数据库/表中。如果该项目不存在,则保存该项目,否则不保存。所以整个用例是同步的。我所做的是将 async.waterfall 嵌套在 async.each 中,因为我认为 async.each 会迭代数组中的每个项目,而 waterfall 会针对每个项目串行执行函数(使用作为参数传递的数据)。但实际情况是,每个函数都针对每个项目执行,然后下一个函数再次针对每个项目执行。不完全是我想要的。

无论如何,这里有一些伪代码:

var async = require('async');
// Assume that connection established to mysql db using mysql module
var testArray = [1,2,3,4];
var eachCounter = 0;
async.each(testArray, function(item,eachCallback){
async.waterfall([
function(callback){
var formattedItem = item + ' some_formatting';
console.log(item + ' > ' + formattedItem);
callback(null, formattedItem);
},
function(arg1, callback){
// Using connection.query here to see if formattedItem exists in a table
var mysqlRows = 0;
if(mysqlRows === 0) {
console.log(arg1 + ' does not exist so save it');
var insertQuery = 'INSERT INTO ...';
callback(null, insertQuery, arg1);
}
else if(mysqlRows > 0) {
console.log(arg1 + ' does exist so don\'t save it');
callback(null, null, arg1);
}
},
function(arg1, arg2, callback){
if(arg1 !== null) {
console.log(arg2 + ' was inserted into mysql table');
callback(null, 'done');
}
else {
console.log(arg2 + ' was not inserted into mysql table');
callback(null, 'done');
}
}
], function (err, result) {
eachCounter++;
if(eachCounter === testArray.length) {
console.log('really done');
}
});
eachCallback();
}, function(err){
if(err) {
console.log('failed');
}
else {
console.log('success')
}
});

结果是:

success
1 > 1 some_formatting
2 > 2 some_formatting
3 > 3 some_formatting
4 > 4 some_formatting
1 some_formatting does not exist so save it
2 some_formatting does not exist so save it
3 some_formatting does not exist so save it
4 some_formatting does not exist so save it
1 some_formatting was inserted into mysql table
2 some_formatting was inserted into mysql table
3 some_formatting was inserted into mysql table
4 some_formatting was inserted into mysql table
really done

当我真正想要的是:

success
1 > 1 some_formatting
1 some_formatting does not exist so save it
1 some_formatting was inserted into mysql table
2 > 2 some_formatting
2 some_formatting does not exist so save it
2 some_formatting was inserted into mysql table
3 > 3 some_formatting
3 some_formatting does not exist so save it
3 some_formatting was inserted into mysql table
4 > 4 some_formatting
4 some_formatting does not exist so save it
4 some_formatting was inserted into mysql table
really done

那么,我做错了什么?谢谢!

最佳答案

async.each 是并行完成的。您想使用async.eachSeries使您的所有调用连续运行。

关于node.js - 使用nodejs、async、falls、each和mysql同步控制流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26523093/

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