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

2

6

Since await does not work inside Array.map or Array.reduce, can you do something like the following or would this be considered misuse of Promise.all? Normally, neo4j.session() would be awaited.

// 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)))
Tench answered 25/10, 2017 at 20:34 Comment(3)
Promise.all(runQueries).then(console.log) is cleanerBrainwashing
@Brainwashing I seriously doubt he actually plans to console.log anything, that's just a stand in for additional business logic.Saccharometer
That is a correct assessment.Tench
P
4

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

No its an array of promises

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

Exactly, When you build the Promises they're executed.

would this be considered misuse of Promise.all?

No this is totally fine, its actually the point of Promise.all.

However you might do (one after another instead of parallel execution) :

(async function(){

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

})()
Parrott answered 25/10, 2017 at 20:37 Comment(4)
what does "build the Promises" mean? is that a babel thing?Brainwashing
@Brainwashing i mean new Promise() with that. If its misleading feel free to editParrott
hmm. he's not using new Promise(), so it's still unclear (more hidden) to noobs. not sure how to clarify...Brainwashing
@Brainwashing i think its fine as it is, if someone is unshure he will probably find our conversation ;)Parrott
C
3

async.await is supposed to be syntactic sugar for sequential promise chains. Considering that database queries are supposed to run concurrently, it's perfectly fine to use await Promise.all(...) in such cases.

Promise.all accepts an array of promises (more specifically, an iterable), and promises start to execute at the moment when they are created. It may be the moment prior to Promise.all call:

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

Or it may be not. If an iterable is not an array but a generator, promises will be lazily created during Promise.all call:

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
Conjugation answered 25/10, 2017 at 20:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.