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);
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: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
theneither directly or indirectly:.then()yourselfPromise.all()which internally calls.then()awaitthe result in anasyncfunction which internally calls.then()