这更多的是一个概念性问题。我了解 Promise 设计模式,但找不到可靠的来源来回答我关于 promise.all()
的问题:
正确的使用场景是什么 promise.all()
或者
有没有可以使用的最佳实践 promise.all()
?理想情况下,只有所有 Promise 对象都具有相同或相似类型时才应该使用它吗?
我唯一能想到的是:
- 使用
promise.all()
如果您想要仅在 promise 对象所有都解决的情况下解决 promise ,如果有一个拒绝则拒绝。
最佳答案
我不确定是否有人真正给出了何时使用Promise.all()
的最通用的解释。 (以及何时不使用它):
What is(are) the correct scenario(s) to use promise.all()
Promise.all()
当您有多个 Promise 并且您的代码想要知道这些 Promise 所代表的所有操作何时成功完成时,这一点非常有用。各个异步操作是什么并不重要。如果它们是异步的,由 Promise 表示,并且您的代码想知道它们何时全部成功完成,则 Promise.all()
正是为了做到这一点而构建的。
例如,假设您需要从三个单独的远程 API 调用收集信息,当您获得所有三个 API 调用的结果时,您需要使用所有三个结果运行一些进一步的代码。这种情况对于Promise.all()
来说是完美的。 。你可以这样:
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()
可能最常用于类似类型的请求(如上面的示例),但没有理由需要这样做。如果您有不同的情况,您需要发出远程 API 请求、读取本地文件并读取本地温度探测器,然后当您拥有来自所有三个异步操作的数据时,您希望对来自所有三个异步操作的数据进行一些处理三,您将再次使用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
});
另一方面,如果您不需要在它们之间进行协调并且可以单独处理每个异步操作,那么您不需要 Promise.all()
。您可以使用各自的 .then()
来触发每个单独的异步操作。处理程序,并且它们之间不需要协调。
此外Promise.all()
有所谓的“快速失败”实现。它返回一个主 promise ,一旦您传递的第一个 promise 被拒绝,它将立即拒绝,或者当所有 promise 都解决时它将解决。所以,要使用Promise.all()
这种类型的实现需要适合您的情况。在其他情况下,您想要运行多个异步操作并且需要所有结果,即使其中一些失败。 Promise.all()
不会直接为您做这件事。相反,您可能会使用类似 Promise.settle()
的内容。对于那种情况。您可以看到an implementation of .settle()
here这使您可以访问所有结果,即使某些结果失败。当您预计某些操作可能会失败,并且您有一项有用的任务需要处理成功的操作的结果,或者您想要检查所有未能据此做出决策的操作的失败原因时,这特别有用。
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?
如上所述,各个异步操作是什么或者它们是否是同一类型并不重要。唯一重要的是您的代码是否需要协调它们并知道它们何时全部成功。
<小时/>列出一些您不使用Promise.all()
的情况也很有用。 :
- 当您只有一个异步操作时。只需一次操作,即可使用
.then()
处理程序只 promise 一个,没有理由Promise.all()
. - 当您不需要在多个异步操作之间进行协调时。
- 当快速失败实现不合适时。如果您需要所有结果,即使某些结果失败,那么
Promise.all()
自己不会这样做。您可能想要类似Promise.allSettled()
的东西相反。 - 如果您的异步操作未全部返回 Promise,
Promise.all()
无法跟踪不是通过 Promise 管理的异步操作。
关于javascript - 何时使用promise.all()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38180080/