全部完成后如何获得多个asynchronous调用的返回值?

我正在使用asynchronous的第三方api方法。 我有需要传递到这个asynchronous方法的项目列表,我想打印出所有的asynchronous调用完成后返回结果的结果。 我知道我可以使用callback来实现这一点。 但是我无法让它工作。 它什么都不打印。 很明显,我在这里使用错误的callback。 是的,我读了这里的callback: https : //github.com/maxogden/art-of-node#callbacks 。 有很好的例子。 但不知道如何使它与asynchronous调用数组合并结合的结果。

var resultArray = []; var items = ["one", "two", "three"]; getResult(items, printResult); function printResult() { for(let j=0; j < resultArray.length; j++) { console.log(resultArray[j]); } } function getResult(items, callback) { for(let i=0; i<items.length; i++) { apiClient.findItem(items[i], function (error, item){ resultArray.push(item.key); }); } } 

正如@JeffreyAGochin指出的那样,你可以用promise来替代它。 如果你不想这样做,你想坚持callback(我不会推荐),你可以使用优秀的asynchronous 。

 function getResult(item, done) { apiClient.findItem(item, done); } async.each(items, getResult, function (error, results) { // if error is null, then all of your results are in 'results' if(error !== null) throw error; results.forEach(function(result) { console.log(result); }); }); 

示例承诺实现(我假设你正在使用ES6,因此由于你的let本身就有Promise)

 // When you are using promises natively (apparently these have performance implications, see comments) your code looks like this: function getResult(item) { return new Promise(function(resolve, reject) { apiClient.findItem(item, function(error, foundItem) { if(error) return reject(error); resolve(foundItem); }); }); } // If you use the excellent bluebird library though (which is pretty common actually), it looks more like this. let apiClient = Bluebird.promisifyAll(apiClient); function getResult(item) { return apiClient.getItemAsync(item); } var resultsPromise = Promise.all(items.map(getResult)); resultsPromise.then(function(results) { results.forEach(function(result) { console.log(result); }); }); 

至于为什么这么多人提出承诺, 这是因为他们构成远远好得多。 还有一些很好的图书馆支持承诺,如高地 (这也是由同一作者作为async以上)把承诺视为一stream的价值。 像这样的callback很难,因为没有真正的方法来“传递”

承诺+1。 有些人喜欢的另一种select是async模块:

 var async = require('async'); async.each( items, function (item, cb) { apiClient.findItem(item, cb); }, function (err, resultArray) { for (let j=0; j < resultArray.length; j++) { console.log(resultArray[j]); } } ); 

我会build议使用Promises库来pipe理所有的asynchronous请求。 他们通常有一个全部的方法,等待所有的承诺完成。 您可以将其他asynchronous库调用包装在承诺中。

https://github.com/kriskowal/q

getResult你没有调用callback参数,所以在这种情况下肯定不会打印任何东西。

如果你坚持使用callback而不是承诺,尽pipe有舆论战争,这是完全可以接受的,一个很好的npm包是Async 。 查看该库中的each函数,它可能会做你想要的。

我认为这是你正在寻找的: http : //howtonode.org/promises 。

我build议你使用一个variables来计算完成的请求,所以你可以检查所有的完成,并做你需要的数组。