什么是最简单/最清洁的方式迭代数组(或objs)asynchronous?

那我怎么做:

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"); }); 

这有什么好处吗? 如何避免这些意大利面代码?

检查asynchronous库,它是为控制stream(asynchronous的东西),它有很多方法数组的东西:每个,filter,地图。 检查github上的文档。 以下是您可能需要的内容:

每个(arr,迭代器,callback)

并行地将迭代器函数应用于数组中的每个项目。 迭代器用列表中的项目和callback完成时调用。 如果迭代器将错误传递给此callback函数,则会立即调用each函数的主callback函数并返回错误。

eachSeries(arr,iterator,callback)

each迭代器相同,只有迭代器被串联​​应用于数组中的每个项目。 下一个迭代器只在当前的迭代器完成处理后才被调用。 这意味着迭代器函数将按顺序完成。

正如在某些答案中指出的,可以使用“asynchronous”库。 但有时你只是不想在代码中引入新的依赖关系。 下面是如何循环和等待一些asynchronous函数完成的另一种方法。

 var items = ["one", "two", "three"]; // This is your async function, which may perform call to your database or // whatever... function someAsyncFunc(arg, cb) { setTimeout(function () { cb(arg.toUpperCase()); }, 3000); } // cb will be called when each item from arr has been processed and all // results are available. function eachAsync(arr, func, cb) { var doneCounter = 0, results = []; arr.forEach(function (item) { func(item, function (res) { doneCounter += 1; results.push(res); if (doneCounter === arr.length) { cb(results); } }); }); } eachAsync(items, someAsyncFunc, console.log); 

现在,运行node iterasync.js将等待大约三秒钟,然后打印[ 'ONE', 'TWO', 'THREE' ] 。 这是一个简单的例子,但它可以扩展到处理很多情况。

正确地指出,你必须使用setTimeout,例如:

 each_async = function(ary, fn) { var i = 0; -function() { fn(ary[i]); if (++i < ary.length) setTimeout(arguments.callee, 0) }() } each_async([1,2,3,4], function(p) { console.log(p) }) 

看看这个项目: 面条 。 它为所有数组extras方法提供asynchronous接口。

有一个新的asynchronous迭代标准: https : //github.com/tc39/proposal-async-iteration

这增加了asynchronous生成器和循环的asynchronous。 for await循环支持来自同步迭代器的转换,并等待将阻止循环。

 async function() { for await(let value of [ 1, 2 ]) { await(Promise.resolve()) console.log(value) } } 

它正在Chrome / Node.js和Firefox中执行 。