我在GitHub 上找到了以下代码,以确保在调用第n个项目处理器的回调之前不会处理第n + 1项。
/**
* Process an array of data synchronously.
*
* @param data An array of data.
* @param processData A function that processes an item of data.
* Signature: function(item, i, callback), where {@code
item} is the i'th item,
* {@code i} is the loop index value and
{@code calback} is the
* parameterless function to call on
completion of processing an item.
*/
function doSynchronousLoop(data, processData, done) {
if (data.length > 0) {
var loop = function(data, i, processData, done) {
processData(data[i], i, function() {
if (++i < data.length) {
loop(data, i, processData, done);
} else {
done();
}
});
};
loop(data, 0, processData, done);
} else {
done();
}
}
我在调用 doSynchronousLoop()方法并编写方法时遇到了困难:processData()和done()。
请帮助我理解代码段,以及如何编写我想要迭代的代码?
答案 0 :(得分:0)
好吧,你可以这样调用你的函数:
let data = [1, 2, 3, 4];
let doSomething = function(item, index, next) {
// item = 1, 2, 3, 4
// when finishing, call next to trigger next function run
// item value will be 2
next();
}
let onDone = function() {
// when all of them are done
}
doSynchronousLoop(data, doSomething, doDone);