【发布时间】:2017-01-22 16:08:21
【问题描述】:
在两个嵌套循环完成迭代后,我在发送填充数组时遇到了困难。我正在使用 Async npm 库并尝试使用 async.forEach 完成回调来发送整个数组。内部数组迭代了 5 个对象,这构成了一个“课程”——之后课程对象被保存到一个人对象中,每个人对象有多个课程对象。
var self = this,
person = [],
course = [];
async.forEach(elements.value, function (element, callback1) {
self.elementIdElements(element.ELEMENT, 'td').then(function (rows) {
async.forEach(rows.value, function (cell, callback2) {
self.elementIdText(cell.ELEMENT).then(function (res) {
course.push(res.value);
callback2();
});
}, callback1);
person.push(course);
course = [];
});
}, function (err) {
res.send('grades: ' + JSON.stringify(person));
});
但是,它在遍历数组的过程中调用了 sendResponse,我根本无法想象为什么会发生这种情况,它应该在遍历整个过程后调用它。范围和异步调用令人困惑
提前致谢, 克里斯
更新 - 解决方案
我终于用下面的代码弄清楚了回调的范围:
var self = this,
person = [],
course = [];
async.forEach(elements.value, function (element, callback1) {
self.elementIdElements(element.ELEMENT, 'td').then(function (rows) {
async.forEach(rows.value, function (cell, callback2) {
self.elementIdText(cell.ELEMENT).then(function (res) {
course.push(res.value);
callback2();
});
}, function (err) {
person.push(course);
course = [];
callback1();
});
});
}, function (err) {
res.send('grades: ' + JSON.stringify(person));
});
【问题讨论】:
-
如果有帮助,请参见下文.. stackoverflow.com/questions/38154395/…
标签: arrays node.js asynchronous foreach callback