如何处理asynchronous函数和集合?

假设我们有一个函数foo(item, callback)和一个集合items

我想要做的就是用项目中的每一个items与执行foo返回的值来replace,就像Array.map()一样。

但问题来了: foo的结果是在callback中产生的,所以我没有在callback本身之外访问它(显然,我不能改变foo来满足我的需要)。

你可以尝试一个像

 var results = []; items.map((function(el) { foo(el, function(result) {results.push(time)}); }); 

但是当你的results收集“准备就绪”的时候你就无法知道了。

我完全无能为力 我该怎么办? 什么是模式?

编辑:我更感兴趣的香草JavaScript的方式来实现这个比工具/库,这是无论如何可以接受的答案。

在香草JS我会这样做:

 var items = ['item 1', 'item 2', 'item 3'] function foo(item, callback) { // this is provided just to test the async nature of your callback setTimeout(function () { callback.call(null, item + ' async') }, Math.random() * 5000); } var results = []; var count = 0; items.forEach(function (element, index, array) { foo(element, function (result) { results[index] = result; // the actual "ready" check if (++count == items.length) { // here you should notify your code that all items have been replaced // after a random number of seconds between 1 and 5 in the current example, it should // write ['item 1 async', 'item 2 async', 'item 3 async'] console.log(results); } }) }); 

我不知道这是一种模式还是最好的方法,但我认为是简单而快速的。 请注意,forEach仅适用于IE9 +。 对于IE <9,你可以使用jQuery。或者手动编写for循环(但要小心闭包和索引)。

使用asynchronous库时,这变得相当微不足道。

 async.each(items, function(el, callback) { foo(el, function(result) { callback(result); }); }, function(results) { doSomethingWith(results); //results being an array of the callbacked results. });