我想将promise推送到一个数组。然后,我想使用Promise.all()
解决它。但是我不确定,当我推送到数组时,promise是否有效?
例如:
const productIds= [1,2,3,4,5,6] // example
const promises = [];
productIds.map(productId => promises.push(ProductDataAccess.updateProductStock(store,productId,incQuery)));
如果我没有Promise.all(),db进程会发生吗?还是我制作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);
答案 0 :(得分:1)
是的,promise是在创建时运行的,而不是在等待它们时(无论是使用Promise.all()
还是其他方式运行)。
答案 1 :(得分:1)
您将start the execution of the promises from the moment each promise is created(无论使用Promise.all
如何),但不要等待它们。
如果此代码块位于async
函数中,则您可以await
这样的诺言(而且,您可以简单地使用map
,而无需push
,以构建所需的承诺数组):
const productIds = [1,2,3,4,5,6];
const promises = productIds.map((productId) => ProductDataAccess.updateProductStock(store,productId,incQuery));
await Promise.all(promises);
答案 2 :(得分:1)
如果我不Promise.all(),会发生数据库进程吗?
这取决于。普遍的回答是是。但是请注意,并非总是如此。
通常,返回Promise的函数在您调用它们时会安排一个异步过程。因此,异步过程将会发生,而与您等待它们的时间无关。
但是,有些功能并没有真正返回承诺。他们返回一个类似诺言的对象。有时(并非总是),除非您调用.then()
,否则它们不会启动异步过程。使用流畅/可链接功能的数据库库可以做到这一点。这是数据库库中的常见设计模式:
// 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!
许多数据库库都这样做以实现对用户透明的流利/链接样式的API。它们通过调用.then()
函数来检测查询构造的结束。
现在,我不知道您正在使用哪个数据库库,但是如果您受到此影响,那么要触发数据库查询过程,您将需要直接调用then
或间接:
.then()
Promise.all()
,内部调用.then()
await
在async
函数中的结果,该函数内部调用.then()