简体   繁体   English

在Promises中使用循环的正确方法

[英]Proper way of using loops in Promises

According to this link (Rookie mistake #2) I should not use loops within Promises, but instead Promise.all(iterable) . 根据这个链接 (Rookie错误#2)我不应该在Promises中使用循环,而是使用Promise.all(iterable)

Does this really apply to all loops? 这真的适用于所有循环吗? Promise.all(iterable) takes an array of size n. Promise.all(iterable)采用大小为n的数组。 If I'd use Promise.all(iterable) , then I'd get as a result (ie iterable_A) an array of the size n. 如果我使用Promise.all(iterable) ,那么我会得到一个大小为n的数组(即iterable_A)。

What if I want to iterate through iterable and only want to put certain elements that satisfy my condition to another iterable (eg iterable_B) and want to return the iterable_B instead of iterable_A? 如果我想迭代遍历iterable并且只想将满足我的条件的某些元素放到另一个iterable(例如iterable_B)并想要返回iterable_B而不是iterable_A,该怎么办? Should I use Promise.all() too? 我也应该使用Promise.all()吗?

I should not use loops within Promises 我不应该在Promises中使用循环

No, rather the other way round: You should not use promises within loops. 不,反之亦然:你不应该在循环中使用promises。

Of course that's too generic as well. 当然那也太通用了。 Sometimes you just need a loop structure. 有时你只需要一个循环结构。 What you must not do is forget to collect the promises that are created in the loop body in some iterable that you can pass to Promise.all , to await all the asynchronous things started in that loop. 你不能做的是忘记在一些可以传递给Promise.all迭代中收集循环体创建的 Promise.all ,以等待在该循环中启动的所有异步事件。

The map method as suggested in the article naturally does that, you just have to return a promise from the callback (as always). 文章中建议的map方法自然会这样做,你只需要从回调中return一个promise(一如既往)。 Using for / while / .forEach makes it a bit harder as you have to manually push the promises in some array (which is not only ugly but also errorprone). 使用for / while / .forEach会让你有点困难,因为你必须手动推送某些数组中的promises(这不仅是丑陋的,而且也是errorprone)。

However, if you are not dealing with asynchronous tasks inside your loop, you can do whatever you want. 但是,如果您不在循环中处理异步任务,则可以执行任何操作。 For example, both 例如,两者

Promise.all(values.filter(syncPredicate).map(asyncFn))

and

Promise.all(promises).then((values) => values.filter(syncPredicate))

are totally fine. 完全没问题。 It does become a bit more complicated when you have an asynchronous filter predicate, I'd recommend to look out for a promise utility library in that case. 当你有一个异步过滤谓词时,它确实变得有点复杂,我建议在这种情况下寻找一个promise实用程序库。

Also you will have to realise that asynchronous tasks started from within a synchronous loop construct will run in parallel. 此外,您必须意识到从同步循环结构中启动的异步任务将并行运行。 If you intend to run them sequentially (await each iteration), you should try to formulate the loop using a recursive structure . 如果您打算按顺序运行它们(等待每次迭代),您应该尝试使用递归结构来表示循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM