How to async way call 10 functions and collect all results and know when all are finished?

前提是你 提交于 2019-12-08 08:42:28

问题


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.


回答1:


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]`
});

E.g.:

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).

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


来源:https://stackoverflow.com/questions/21392901/how-to-async-way-call-10-functions-and-collect-all-results-and-know-when-all-are

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!