使用环回,我有一个简单的 for 循环,在其中执行 findOne:
let my_data = [];
Orders.forEach(function(order,idx) {
let postalcode = order.toJSON().customer.postal_code;
let ps4 = postalcode.slice(0,4);
app.models.postalcode.findOne({where: {postal_code: parseInt(ps4)},include: ['depot']}, function (err, Postalcode) {
if (err) {
winston.error('Could not load postalcode %s due to error %s: ', ps4, err.message);
} else {
if (Postalcode) {
let depot = Postalcode.toJSON().depot;
if (!depot) {
//
} else {
let depot_city = depot.city;
if (cities_to_process.indexOf(depot_city) > -1) {
my_data.push(order);
} else {
}
}
} else {
winston.warn('Could not find postal code %s', ps4)
}
}
});
});
console.log(my_data);
在 for 循环之后,我想对 my_data 中收集的数据执行一些操作。由于 findOne 似乎是异步的,那么执行此操作的首选方法是什么?
最佳答案
使用async
库。您可以轻松使用 async.eachSearies()
串联循环 async
函数并获得所需的输出。您可以引用这里link
关于node.js - 环回: how to collect data in a for-loop containing a async method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52178863/