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)))
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)))
Share
Improve this question
edited Nov 13, 2017 at 5:42
agm1984
asked Oct 25, 2017 at 20:34
agm1984agm1984
17.2k6 gold badges104 silver badges117 bronze badges
3
-
Promise.all(runQueries).then(console.log)
is cleaner – dandavis Commented Oct 25, 2017 at 20:59 - 1 @dandavis I seriously doubt he actually plans to console.log anything, that's just a stand in for additional business logic. – skylize Commented Nov 13, 2017 at 4:23
- That is a correct assessment. – agm1984 Commented Nov 13, 2017 at 5:42
2 Answers
Reset to default 4Does 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));
})()
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