【发布时间】:2011-12-07 10:30:39
【问题描述】:
我就是这样做的:
function processArray(array, index, callback) {
processItem(array[index], function(){
if(++index === array.length) {
callback();
return;
}
processArray(array, index, callback);
});
};
function processItem(item, callback) {
// do some ajax (browser) or request (node) stuff here
// when done
callback();
}
var arr = ["url1", "url2", "url3"];
processArray(arr, 0, function(){
console.log("done");
});
有什么好处吗?如何避免那些意大利面条式的代码?
【问题讨论】:
-
使用jQuery,可以使用
$.each([...], function() {...});,其他JS库中也会有类似的方法。 -
是的,但它们是同步的。 Aron 正在询问异步循环,这是一个更有趣的问题!
-
2016,我今天用过这个。应该看看 ES6 但是...谢谢!
标签: javascript node.js