Promise.all() 是执行一个函数数组还是当你将它们放入数组时执行?

Does Promise.all() execute an array of functions or do they execute when you put them into the array?

因为 awaitArray.mapArray.reduce 中不起作用,你能做类似下面的事情吗?或者这会被认为是滥用 Promise.all 吗?通常,会等待 neo4j.session()

// inside a function

const QUERY = 'MATCH (n) RETURN n'
const argsArray = [{ sample: 'sadf' }, { sample: 'sadf' }, { sample: 'sadf' }]

const runQueries = argsArray.map(obj => neo4j.session.run(QUERY, obj.sample))

await Promise.all(runQueries)
      .then(results => results.forEach(result => console.log(result)))

Does Promise.all() execute an array of functions?

不,它是一系列承诺

or do they execute when you put them into the array?

确切地说,当您构建 Promise 时,它​​们就会被执行。

would this be considered misuse of Promise.all?

不,这完全没问题,它实际上是 Promise.all 的要点。

但是你可能会这样做(一个接一个而不是并行执行):

(async function(){

for(const obj of argsArray)
  console.log( await neo4j.session.run(QUERY, obj.sample));

})()

async.await 应该是顺序承诺链的语法糖。考虑到数据库查询应该同时 运行,在这种情况下使用 await Promise.all(...) 是完全没问题的。

Promise.all 接受一个 promises 数组(更具体地说,一个可迭代对象),并且 promises 在它们被创建的那一刻开始执行。可能是 Promise.all 调用之前的时刻:

const promises = [Promise.resolve(1), Promise.resolve(2)];
// promises have been created at this point
Promise.all(promises).then(...)

也可能不是。如果可迭代对象不是数组而是生成器,将在 Promise.all 调用期间延迟创建承诺:

const promiseGen = (function* () {
  yield Promise.resolve(1);
  yield Promise.resolve(2);
})();
// promises have not been created yet at this point
Promise.all(promiseGen).then(...)
// promises have been created