我使用嵌套for循环来完成任务。我发现HTTP调用和数据库查询是异步的,最终会产生不希望的输出。所以我使用了async.eachOfSeries。执行在第一次迭代本身进入内部最async.eachOfSeries后立即停止。我想我在构造代码和返回回调时犯了一些错误。我基本上需要知道你的两件事:
我们将不胜感激。
async.eachOfSeries(res, function (value, camp, callback) {
let _id = res[camp]._id;
let arr = res[camp].campaignID;
async.eachOfSeries(arr, function (value1, i, callback) {
let users = arr[i].users;
let id = arr[i].id;
let loop = Math.ceil(users / 1000);
let limit = 0,
offset = 0;
for (let j = 0; j < loop; j++) {
if (users > 1000) {
limit = 1000;
users -= limit;
} else {
limit = users;
}
console.log(limit + " limit " + offset + " offset");
var start = Date.now();
while (Date.now() < start + 100) {}
const request = mailjet
.get("messagesentstatistics")
.request({
"CampaignID": id,
"AllMessages": true,
"Limit": limit,
"Offset": offset
})
request
.then((result) => {
let data = result.body.Data;
var loop = 0;
async.eachOfSeries(data, function (value2, val, callback) {
console.log("ayyuuuuu");
let jsonObj = data[val];
let email = jsonObj.ToEmail;
jsonObj['retailer'] = res[camp].retailer;
jsonObj['summary'] = 'f';
let tempObj = {};
tempObj[id] = jsonObj;
let options = {
new: true
};
let campId = id;
User.addCampaignResponse(email, campId, tempObj, options, function (err, results) {
if (err) {
throw err;
} else {
Campaign.updateResponse(_id, function (err, results2) {
if (err)
throw err;
}) // console.log(results);
}
})
}, function (err) {
callback();
})
})
.catch((err) => {
console.log(err);
})
offset += limit;
}
}, function (err) {
callback();
})
}, function (err) {
callback(undefined, "doneeeeee");
})