Is the promise resolved, when I push promise array?

145 Views Asked by At

I want to push promise to an array. Then I want to resolve it using Promise.all(). But I'm not sure, is promise work when i push to array?

For example:


const productIds= [1,2,3,4,5,6] // example
const promises = [];
productIds.map(productId => promises.push(ProductDataAccess.updateProductStock(store,productId,incQuery)));

If I don't Promise.all(), will db process occur? Or does the db process occur when I make Promise.all().


const productIds= [1,2,3,4,5,6] // example
const promises = [];
productIds.map(productId => promises.push(ProductDataAccess.updateProductStock(store,productId,incQuery)));
Pormise.all(promises);
3

There are 3 best solutions below

0
On BEST ANSWER

If I don't Promise.all(), will db process occur?

It depends. The general answer is yes. But be aware that this is not always true.

Normally, functions that return a Promise schedules an asynchronous process when you call them. So the asynchronous process will happen regardless of you waiting for them.

However, there are some functions that don't really return a promise. They return a promise-like object. And sometimes (not always) they don't start the asynchronous process unless you call .then(). And database libraries that use fluent/chainable functions do this. This is a common design pattern in database libraries:

// knex example:

let x = knex('my_table').select(['id','some_info']); // will not trigger db query
console.log(x); // knex object - not a Promise!

x = x.where('id', 0); // still no db query
console.log(x); // still not a Promise!

x = x.then(result => console.log(result)); // TRIGGERS DB QUERY!
console.log(x); // Yay! A Promise!

Lots of database libraries do this in order to implement a fluent/chaining style API that is transparent to the user. They detect the end of query construction by the .then() function being called.

Now, I don't know what database library you are using but if you are affected by this then to trigger the database query process you will need to call then either directly or indirectly:

  • call .then() yourself
  • pass the object to Promise.all() which internally calls .then()
  • await the result in an async function which internally calls .then()
0
On

Yes, promises run when they are created, not when they are awaited upon (be it with Promise.all() or otherwise).

2
On

You will start the execution of the promises from the moment each promise is created (regardless of the usage of Promise.all), but not wait for them.

If this block of code is in an async function, you can await the promises in this way (and also, you can simply use map, without push, to build the array of promises you need):

const productIds = [1,2,3,4,5,6];
const promises = productIds.map((productId) => ProductDataAccess.updateProductStock(store,productId,incQuery));

await Promise.all(promises);