节点:使用 promise.all() 并行调用 API?

fro*_*uma 1 javascript node.js promise

我有点困惑 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)

Run Code Online (Sandbox Code Playgroud)

据我观察, Promise.all 并行运行承诺,并等待所有承诺完成。

T.J*_*der 6

它是否并行运行承诺数组

Promise.all没有,没有;您的代码可以(好吧,可能;请参阅下面的注释)。在看到承诺之前,这项工作已经在进行中Promise.all。什么Promise.all是给你一个承诺,当你给它的所有承诺都实现(或其中一个被拒绝)时,它就会解决。

这是你的代码,使并行工作的运行,通过启动承诺报告完成(在行动map,以给他们的回调)Promise.all摆在首位。见***评论:

// *** `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)
Run Code Online (Sandbox Code Playgroud)

请记住,promise 只是观察异步过程完成的一种方式。Promise 不会运行任何东西。他们只是报告某事的完成情况,以及履行价值或拒绝原因。


笔记

如果this.getSomething(sample, args)返回一个承诺,你的代码就会成为显式承诺创建反模式的牺牲品:根本没有理由在new Promise这里使用。反而:

const arrayOfPromises = sampleArray.map(sample => this.getSomething(sample, args));
Run Code Online (Sandbox Code Playgroud)

如果this.getSomething(sample, args)立即返回它的值,那么在这里使用 Promise 根本没有意义,因为在它返回时操作已经完成。

(我假设它不会启动异步进程并通过回调而不是承诺报告完成,因为您没有显示回调但您已使用返回值显示。)

getSomething你的问题已经证明返回一个承诺(因为它是一个async功能),但你不认为这是因为this.getSomething(...),就如getSomething(...)