[英]Node.js async array iteration
I am trying to synchronously iterate over an array using async.each
: 我正在尝试使用
async.each
同步迭代数组:
async.each(supplier_array, function(supplier) {
console.log('looking at : ' + supplier);
knex(host_name + '.order_item').where({
supplier: supplier,
order_id: order_id
}).then(function(data) {
console.log(data);
knex(host_name + '.distributor').select()
.then(function(data) {
console.log(data);
}).catch(function(error) {
console.log('error: ' + error);
});
}).catch(function(error) {
console.log('error: ' + error);
});
});
My supplier_array
has 3 elements. 我的
supplier_array
有3个元素。 So what SHOULD happen is the app should (synchronously): 因此,应该发生的是应用程序应该(同步):
For supplier 1 / first arr / first array element: 对于供应商1 /第一区域/第一数组元素:
For supplier 2 / second array element: 对于供应商2 /第二个数组元素:
For supplier 3 / third array element: 对于供应商3 /第三个数组元素:
HOWEVER, it acts asynchronously: 但是,它异步运行:
console.log(supplier) 执行console.log(供应商)
console.log(order_item) 执行console.log(order_item)
console.log(order_item) 执行console.log(order_item)
console.log(distributor) 的console.log(分配器)
Can someone help me achieve the desired effect of running through the steps inside of async
synchronously? 有人可以帮助我达到同步运行
async
内部步骤的预期效果吗?
Thanks in advance! 提前致谢!
You should use async.eachSeries
if you want to iterate them in serial order. 如果
async.eachSeries
顺序迭代它们,则应使用async.eachSeries
。 Try something like this: 尝试这样的事情:
async.eachSeries(supplier_array, function(supplier, callback) {
console.log('looking at : ' + supplier);
knex(host_name + '.order_item').where({
supplier: supplier,
order_id: order_id
}).then(function(data) {
console.log(data);
knex(host_name + '.distributor').select()
.then(function(data) {
console.log(data);
callback(); // Advance to next iteration here
}).catch(function(error) {
console.log('error: ' + error);
callback(error); // Also callback when error occurs
});
}).catch(function(error) {
console.log('error: ' + error);
callback(error); // Also callback when error occurs
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.