如何异步方式调用10个函数并收集所有结果并知道什么时候完成? [英] How to async way call 10 functions and collect all results and know when all are finished?
问题描述
我正在使用Node.js的延迟模块,我创建了从远程服务器获取数据的延迟函数。我需要从不同的远程服务器获取10个文件,如何做到这一点,承诺知道什么时候完成并获取所有然后结果数组?
目前我已经关闭了,只有当我完成之前的操作时我才会获取下一个文件,但它同步且速度慢。
I am using deferred module for Node.js and I have created deferred functions which fetch data from distant server. I need to fetch 10 files from different distant server, how to do this with promise to know when all are finished and fetch all then results in array ? At the moment I have closure and I am fetching next file only when I have done with previous but it is sync and slow.
推荐答案
根据我所假设的文档是你正在使用的模块,你可以这样做:
According to the documentation of what I assume is the module you're using, you can do this:
deferred(delayedAdd(2, 3), delayedAdd(3, 5), delayedAdd(1, 7))(function (result) {`
console.log(result); // [5, 8, 8]`
});
例如:
deferred(promise1, promise2, promise3)(function (result) {
// `result` is an array of the results
});
在上面的链接中,搜索分组承诺(尽管它没有多少以上)。
On the link above, search for "Grouping Promises" (although it doesn't have much more than the above).
如果您有一系列承诺,可以使用 函数#apply
执行上述操作:
If you have an array of promises, you can use Function#apply
to do the above:
deferred.apply(undefined, theArray)(function (result) {
// `result` is an array of the results
});
这篇关于如何异步方式调用10个函数并收集所有结果并知道什么时候完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!