何时使用 promise.all()? [英] When to use promise.all()?

查看:25
本文介绍了何时使用 promise.all()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更像是一个概念性问题.我了解 Promise 设计模式,但找不到可靠的来源来回答我关于 promise.all() 的问题:

什么是使用promise.all()

的正确场景

是否有使用 promise.all() 的最佳实践?是否应该仅在所有 Promise 对象的类型相同或相似时才使用它?

我唯一能想到的是:

  • 使用 promise.all() 如果你想解决承诺 only 如果 all 承诺对象解决和拒绝,如果甚至一个拒绝.

解决方案

我不确定是否有人真正给出了关于何时使用 Promise.all()(以及何时使用)的最通用的解释不要使用它):

<块引用>

使用 promise.all() 的正确场景是什么

Promise.all() 在您有多个承诺并且您的代码想知道这些承诺代表的所有操作何时成功完成时非常有用.各个异步操作是什么并不重要.如果它们是异步的,由 promise 表示,并且您的代码想知道它们何时全部成功完成,那么 Promise.all() 就是为了做到这一点而构建的.

例如,假设您需要从三个单独的远程 API 调用中收集信息,并且当您获得所有三个 API 调用的结果时,您就需要使用所有三个结果运行一些进一步的代码.这种情况对于 Promise.all() 来说是完美的.你可以这样:

Promise.all([apiRequest(...), apiRequest(...), apiRequest(...)]).then(function(results) {//API 结果在此处的结果数组中//处理可以继续使用所有三个 API 请求的结果}, 函数(错误){//发生错误,在此处理错误});

Promise.all() 可能最常用于类似类型的请求(如上例所示),但没有理由必须如此.如果你有一个不同的情况,你需要发出一个远程 API 请求,读取一个本地文件并读取一个本地温度探测器,然后当你有来自所有三个异步操作的数据时,你想要对所有数据进行一些处理三、你会再次使用Promise.all():

Promise.all([apiRequest(...), fs.promises.readFile(...), readTemperature(...)]).then(function(results) {//这里的结果数组中的所有结果//处理可以继续使用所有三个异步操作的结果}, 函数(错误){//发生错误,在此处理错误});

另一方面,如果您不需要在它们之间进行协调并且可以单独处理每个异步操作,那么您就不需要 Promise.all().您可以使用自己的 .then() 处理程序触发每个单独的异步操作,并且不需要它们之间的协调.

此外 Promise.all() 具有所谓的快速失败"执行.它返回一个主承诺,一旦您通过它的第一个承诺被拒绝,它就会拒绝,或者当所有承诺都已解决时它将解决.因此,要使用 Promise.all() 这种类型的实现需要适合您的情况.在其他情况下,您想要运行多个异步操作并且您需要所有结果,即使其中一些失败.Promise.all() 不会直接为你做这件事.相反,您可能会在这种情况下使用类似 Promise.settle() 的东西.你可以看到.settle() 此处 可让您访问所有结果,即使有些结果失败.当您预计某些操作可能会失败并且您有一项有用的任务需要使用任何成功操作的结果时,或者您想检查所有未能基于此做出决策的操作的失败原因时,这尤其有用.<块引用>

是否有使用 promise.all() 的最佳实践?应该是理想情况下,仅当所有承诺对象都相同或类似的类型?

如上所述,单个异步操作是什么或者它们是否是相同类型都无关紧要.重要的是您的代码是否需要协调它们并知道它们何时全部成功.


列出一些您使用Promise.all()的情况也很有用:

  1. 当您只有一个异步操作时.只需一个操作,您就可以在一个 promise 上使用 .then() 处理程序,而没有理由使用 Promise.all().
  2. 当您不需要在多个异步操作之间进行协调时.
  3. 当快速失败实施不合适时.如果您需要所有结果,即使有些结果失败,那么 Promise.all() 本身不会这样做.你可能想要像 Promise.allSettled() 这样的东西.
  4. 如果您的异步操作没有全部返回承诺,Promise.all() 无法跟踪未通过承诺管理的异步操作.

This is more of a conceptual question. I understand the Promise design pattern, but couldn't find a reliable source to answer my question about promise.all():

What is(are) the correct scenario(s) to use promise.all()

OR

Are there any best practices to use promise.all()? Should it be ideally used only if all of the promise objects are of the same or similar types?

The only one I could think of is:

  • Use promise.all() if you want to resolve the promise only if all of the promise objects resolve and reject if even one rejects.

解决方案

I'm not sure anyone has really given the most general purpose explanation for when to use Promise.all() (and when not to use it):

What is(are) the correct scenario(s) to use promise.all()

Promise.all() is useful anytime you have more than one promise and your code wants to know when all the operations that those promises represent have finished successfully. It does not matter what the individual async operations are. If they are async, are represented by promises and your code wants to know when they have all completed successfully, then Promise.all() is built to do exactly that.

For example, suppose you need to gather information from three separate remote API calls and when you have the results from all three API calls, you then need to run some further code using all three results. That situation would be perfect for Promise.all(). You could so something like this:

Promise.all([apiRequest(...), apiRequest(...), apiRequest(...)]).then(function(results) {
    // API results in the results array here
    // processing can continue using the results of all three API requests
}, function(err) {
    // an error occurred, process the error here
});

Promise.all() is probably most commonly used with similar types of requests (as in the above example), but there is no reason that it needs to be. If you had a different case where you needed to make a remote API request, read a local file and read a local temperature probe and then when you had data from all three async operations, you wanted to then do some processing with the data from all three, you would again use Promise.all():

Promise.all([apiRequest(...), fs.promises.readFile(...), readTemperature(...)]).then(function(results) {
    // all results in the results array here
    // processing can continue using the results of all three async operations
}, function(err) {
    // an error occurred, process the error here
});

On the flip side, if you don't need to coordinate among them and can just handle each async operation individually, then you don't need Promise.all(). You can just fire each of your separate async operations with their own .then() handlers and no coordination between them is needed.

In addition Promise.all() has what is called a "fast fail" implementation. It returns a master promise that will reject as soon as the first promise you passed it rejects or it will resolve when all the promises have resolved. So, to use Promise.all() that type of implementation needs to work for your situation. There are other situations where you want to run multiple async operations and you need all the results, even if some of them failed. Promise.all() will not do that for you directly. Instead, you would likely use something like Promise.settle() for that situation. You can see an implementation of .settle() here which gives you access to all the results, even if some failed. This is particularly useful when you expect that some operations might fail and you have a useful task to pursue with the results from whatever operations succeeded or you want to examine the failure reasons for all the operations that failed to make decisions based on that.

Are there any best practices to use promise.all()? Should it be ideally used only if all of the promise objects are of the same or similar types?

As explained above, it does not matter what the individual async operations are or if they are the same type. It only matters whether your code needs to coordinate them and know when they all succeed.


It's also useful to list some situations when you would not use Promise.all():

  1. When you only have one async operation. With only one operation, you can just use a .then() handler on the one promise and there is no reason for Promise.all().
  2. When you don't need to coordinate among multiple async operations.
  3. When a fast fail implementation is not appropriate. If you need all results, even if some fail, then Promise.all() will not do that by itself. You will probably want something like Promise.allSettled() instead.
  4. If your async operations do not all return promises, Promise.all() cannot track an async operation that is not managed through a promise.

这篇关于何时使用 promise.all()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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