如何解决节点:是否使用promise.all并行调用API?
我有点困惑promise.all如何工作,它是否并行运行promise数组?
这是示例代码
// index.js
const getSomething = async (args) => {
return await apiCallHere(args)
}
// Create Array of Promises
const arrayOfPromises = sampleArray.map(sample => new Promise((resolve,reject) => {
try {
const something = this.getSomething(sample,args)
resolve(something)
} catch (error) {
reject(error)
}
}))
await Promise.all(arrayOfPromises)
根据我的观察,Promise.all并行运行promise,并等待所有promise 完成。
解决方法
它是否并行运行承诺数组
Promise.all
不,不; 您的代码可以(可能;请参见下面的注释)。在Promise.all
兑现诺言之前,这项工作已经在进行中。 Promise.all
所做的就是给您一个承诺,该承诺将在您提供的所有承诺都得到兑现(或其中一个被拒绝)时解决。
您的代码可以使工作并行运行,方法是开始执行承诺报告的操作(在map
回调中),以便将其交给{{ 1}}。查看Promise.all
条评论:
***
请记住,promise只是观察异步过程完成情况的一种方法。承诺不会运行。他们只是报告某件事的完成情况,以及实现价值或拒绝原因。
注释
如果// *** `map` is synchronous,it loops all the way through the array
const arrayOfPromises = sampleArray.map(sample => new Promise((resolve,reject) => {
try {
const something = this.getSomething(sample,args) // *** This is what starts each thing
resolve(something)
} catch (error) {
reject(error)
}
}))
// *** The work is already underway here
// *** This just waits for it to finish
await Promise.all(arrayOfPromises)
返回了一个承诺,则您的代码将成为explicit promise creation anti-pattern的牺牲品:根本没有理由在这里使用this.getSomething(sample,args)
。相反:
new Promise
如果const arrayOfPromises = sampleArray.map(sample => this.getSomething(sample,args));
立即返回其值,则根本没有必要在此处使用promise,因为在返回时操作已经完成。
(我假设它不会启动异步过程,而是通过回调而不是promise来报告完成,因为您没有显示回调,但已经显示使用返回值。)
您在问题中显示的this.getSomething(sample,args)
返回了一个promise(因为它是一个getSomething
函数),但是您不会像{{1 }}。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。