Javascript 当I';I’我想在一个承诺的范围内把价格加起来
我试图从API(firebase)中提取数据,并获取正确的数据,但当我尝试解决承诺中的最终价格时,我始终得到0的值。我试着改变原始变量的作用域,但到目前为止没有任何效果Javascript 当I';I’我想在一个承诺的范围内把价格加起来,javascript,scope,es6-promise,Javascript,Scope,Es6 Promise,我试图从API(firebase)中提取数据,并获取正确的数据,但当我尝试解决承诺中的最终价格时,我始终得到0的值。我试着改变原始变量的作用域,但到目前为止没有任何效果 const staffTotalPrices = (eventFirebaseKey) => new Promise((resolve, reject) => { eventStaff.getEventStaff(eventFirebaseKey).then((staffArray) => { le
const staffTotalPrices = (eventFirebaseKey) => new Promise((resolve, reject) => {
eventStaff.getEventStaff(eventFirebaseKey).then((staffArray) => {
let staffTotal = 0;
staffArray.forEach((staff) => {
staffData.getSingleStaff(staff.staffUid).then((staffObject) => {
staffTotal += parseInt(staffObject.price, 10);
return staffTotal;
});
});
resolve(staffTotal);
}).catch((error) => reject(error));
});
我一直在将它推到一个空数组,然后使用.reduce数组方法来添加总数,但是我在调用它/减少它时必须设置一个超时,以等待API响应,在您的
forEach
循环中,您正在调用一个异步函数,但不等待其结果。因此,您在调用任何staffData.getSingleStaff
resolved之前调用resolve(staffTotal)
例如,您可以执行一个任务,该任务将执行所有承诺并使用一组结果进行解析
const staffTotalPrices = (eventFirebaseKey) => new Promise((resolve, reject) => {
eventStaff.getEventStaff(eventFirebaseKey)
//execute getSingleStaff for all elements in the array and resolve when all are resolved
.then(staffArray => Promise.all(staffArray.map(staff => staffData.getSingleStaff(staff.staffUid))))
//sum up the prices in the staffObjects array with reduce
.then(staffObjects => staffObjects.reduce((a,c) => parseInt(a.price, 10) + parseInt(c.price, 10), 0))
//resolve the promise with the sum
.then(totalStaff => resolve(totalStaff));
.catch((error) => reject(error));
});
另一种可能性是,在forEach循环中保留已解决承诺的计数。一旦,所有的承诺都解决了,也解决了外部的承诺。但是,当然,你们也需要抓住内心承诺的拒绝,否则,若其中一个拒绝了你们的承诺,你们的承诺可能会停留在等待状态
const staffTotalPrices = (eventFirebaseKey) => new Promise((resolve, reject) => {
eventStaff.getEventStaff(eventFirebaseKey).then((staffArray) => {
let staffTotal = 0; let resolveCounter = 0;
staffArray.forEach((staff) => {
staffData.getSingleStaff(staff.staffUid)
.then((staffObject) => {
staffTotal += parseInt(staffObject.price, 10);
if (++resolveCounter == staffArray.length)
resolve(staffTotal);
})
.catch(e => reject(e));
});
}).catch((error) => reject(error));
});