如何在for循环中创建Promise之后使用Promise.all() [英] How to use Promise.all() after Promises created in for loop

查看:2397
本文介绍了如何在for循环中创建Promise之后使用Promise.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数foo(),它包含一个在for循环中解析的Promise。我想多次运行foo(),每次都给它不同的参数。然后我想对所有这些的结果做些什么。 Promise.all()会在for循环结束时运行还是在foo()内部的所有Promise都返回后运行?或者它会说这些foo()都不是Promise!并嘲笑我?

I have a function foo() that includes a Promise that resolves inside a for loop. I want to run foo() several times, giving it different arguments each time. Then I want to do something with the results of all of that. Will Promise.all() run at the end of the for loops or after all of the Promises inside of foo() returned? Or will it say "none of these foo()s are Promises!" and laugh at me?

var foo = (x) => {
    for (var i = 0; i < 100; i++) {
        someOtherFunctionThatReturnsAPromise(x).then(returnSomething());
    }
};

function nowDoEverything() {
    return Promise.all([foo(1), foo(2), foo(3)]).then(doSomethingWithAllThoseReturnedValues());
}

nowDoEverything();

foo()是否需要返回Promise?如果是这样,假如foo()内部的Promises是在for循环中生成的,我该如何做?

Does foo() need to return a Promise? If so, how would I do so given that the Promises inside of foo() are generated inside the for loop?

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise / all 表示
Promise.all(iterable)方法返回一个promise,它在iterable参数中的所有promise都已解析时解析,或者因为第一个传递的promise拒绝的原因而拒绝。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all states that "The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects."

此视频 https ://www.youtube.com/watch?v = RRgAdi3gX-s 非常善于解释基本的Promises,但我似乎正在尝试做一些建筑师不打算/期望的事情。

This video https://www.youtube.com/watch?v=RRgAdi3gX-s is really good at explaining basic Promises, but I seem to be trying to do something that the architects did not intend/expect.

推荐答案

将承诺推送到数组, foo返回数组,从功能中省略() .then()内的离子,以避免立即调用函数。在 foo()调用中使用spread元素将单个promises数组返回到 .then()链接到 Promise.all()

Push promises to an array, return array from foo, omit () from function within .then() to avoid calling function immediately. Use spread element at foo() calls to return a single array of promises to .then() chained to Promise.all().

var foo = (x) => {
    var arr = [];
    for (var i = 0; i < 100; i++) {
        arr.push(someOtherFunctionThatReturnsAPromise(x).then(returnSomething));
    }
    return arr
};

function nowDoEverything() {
    return Promise.all([...foo(1), ...foo(2), ...foo(3)])
           .then(doSomethingWithAllThoseReturnedValues)
}

nowDoEverything()
.catch(err => console.log(err));

这篇关于如何在for循环中创建Promise之后使用Promise.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆