我有以下数据结构,将collection
document
{
".......": "......." //few more properties
"productInfo": {
"0": {
"code": "SC05",
"price": 400,
"productId": "asUsd1HPEPOo2itiKxdash",
".......": "......." //few more properties
"addOns": [{
"aid": "4casedasgdfdgfas",
"price": "50",
"......": "....." //few more properties
}]
}
}
}
所以我将拥有一系列产品对象,每个产品都会有一些addon对象。
我尝试在将其保存为文档之前从db检索价格,因此我为该特定表编写了.onCreate
函数。要在product
级别和addon
级别检索价格,我有2个承诺如下:
const productPromises = [];
_.map(products, (product) => {
productPromises.push(new Promise((resolve, reject) => {
db.doc(`product/${product.productId}`).get().then(docData => {
return resolve({
productId: product.productId,
halfkgprice: docData.data().halfkgprice,
price: docData.data().price
});
}).catch(reason => {
return reject(reason);
});
}));
});
const addonPromise = [];
_.map(products, (product) => {
addonPromise.push(new Promise((resolve, reject) => {
if (product.addOns !== undefined && product.addOns !== null) {
return _.map(product.addOns, (addon) => {
return db.doc(`addons/${addon.aid}`).get().then((addonData) => {
return resolve({
price: addonData.data().price
});
}).catch(reason => {
return reject(reason);
})
});
} else {
return resolve();
}
}));
});
然后我确实
Promise.all([productPromises, addonPromise]).then(result => {
//do something with result
});
但这不会等待任何解决的承诺。当我记录结果时,我得到如下。
console.log(result) will show [ [ Promise { <pending> } ], [ Promise { <pending> } ] ] and doesn't wait for them to resolve
我的问题是,为什么不等待所有的承诺来解决?我从firestore
获取query
?
答案 0 :(得分:2)
productPromises
和addonPromise
是promises数组,因此传递给Promise.all
的数组是一个数组数组,而不是一个promises数组 - 试试
Promise.all([...productPromises, ...addonPromise]).then
另外,避免使用Promise构造函数反模式
_.map(products, (product) => {
productPromises.push(
db.doc(`product/${product.productId}`).get().then(docData => {
return ({
productId: product.productId,
halfkgprice: docData.data().halfkgprice,
price: docData.data().price
});
})
);
});
答案 1 :(得分:1)
您需要连接2个数组才能使其按预期工作
Promise.all(productPromises.concat(addonPromise)).then(result => {
//do something with result
});
答案 2 :(得分:0)
map
构建一个返回值数组,因此您只需编写:
const productPromises = _.map(products, product => db.doc(`product/${product.productId}`).get()
.then(docData => ({
productId: product.productId,
halfkgprice: docData.data().halfkgprice,
price: docData.data().price
})
);