在承诺使用循环的正确方法 [英] Proper way of using loops in Promises

查看:212
本文介绍了在承诺使用循环的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个链接 (新手的错误#2)我不应该承诺中使用的循环,而是 Promise.all(迭代器)

这是否真的适用于所有的循环? Promise.all(迭代器)采用大小为n的数组。如果我会使用 Promise.all(迭代器),那么我会得到一个结果(即iterable_A)大小为n的数组。

如果我想通过迭代迭代,只希望把满足我的状态向另一种迭代(例如iterable_B),并希望返回iterable_B而不是iterable_A某些要素是什么?我应该使用 Promise.all()吗?


解决方案

  

我不应该使用的承诺范围内的循环


没有,而反过来想:你不应该在循环中使用的承诺。

当然,这是过于笼统为好。有时候,你只需要一个循环结构。什么你不能做的是的忘了收集了在循环体的一些迭代创建的承诺,你可以传递给 Promise.all ,等待所有在该循环开始异步的东西。

地图方法,在文章中建议自然也说,你只需要收益 从回调的承诺(一如既往)。使用 / ,而 / .forEach 使得它有点因为你必须手动推一些阵列的承诺(这不仅难看,而且容易出错)更难了。

不过,如果你不处理你的循环中异步任务,你可以做任何你想要的。例如,这两个

  Promise.all(values​​.filter(同步predicate).MAP(asyncFn))

  Promise.all(承诺)。然后((值)=> values​​.filter(同步predicate))

是完全的罚款。它变得更加复杂一点,当你有一个异步的过滤器predicate,我建议你看出来在这种情况下诺言工具库。

你也必须意识到,异步任务从同步循环结构内启动将并行运行。如果你打算按顺序运行它们(每次迭代的await),你应该尝试使用递归结构制定循环

According to this link (Rookie mistake #2) I should not use loops within Promises, but instead Promise.all(iterable).

Does this really apply to all loops? Promise.all(iterable) takes an array of size n. If I'd use Promise.all(iterable), then I'd get as a result (i.e. iterable_A) an array of the size n.

What if I want to iterate through iterable and only want to put certain elements that satisfy my condition to another iterable (e.g. iterable_B) and want to return the iterable_B instead of iterable_A? Should I use Promise.all() too?

解决方案

I should not use loops within Promises

No, rather the other way round: You should not use promises within loops.

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.

The map method as suggested in the article naturally does that, you just have to return a promise from the callback (as always). 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).

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.

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.

这篇关于在承诺使用循环的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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