【发布时间】:2017-01-02 06:41:37
【问题描述】:
只有在所有的 promise 都解决之后,你必须在循环中等待循环中的异步调用,你如何执行一个函数?
代码被简化到最低限度
$scope.book = function(input) {
//Get the cart items from DB
ref.child('/cart/' + userId).once('value').then(function(cartSnap) {
//Loop through the cart items
cartSnap.forEach(function(cartItemSnap) {
var itemId = cartItemSnap.key();
//Get the inventory items from DB that are in the cart
ref.child('/inventory/' + itemId).once('value').then(function(inventoryItem) {
//Loop through booking IDs of inventoryItem
inventoryItem.child('rentals').forEach(function(rentalSnap) {
var rentalId = rentalSnap.key();
//Get bookings from rental/active
ref.child('/rental/'+ rentalId).once('value').then(function(activeRentals) {
checkIfBookingIsAllowed();
});
});
});
});
//Once everything was checked
bookRental();
});
};
为了提高速度,所有请求都可以并行发出,但最终函数 bookRental() 只能在一切都解决后调用。
感谢您的帮助。
编辑: 又一次失败的尝试。 Promise.all('collector') 在所有承诺解决之前被触发。所以“完成”出现在控制台中的所有“检查”之前。
$scope.book = function(input) {
//Get the cart items from DB
ref.child('/cart/' + userId).once('value').then(function(cartSnap) {
//Promise collector
var collector = [];
//Loop through the cart items
cartSnap.forEach(function(cartItemSnap) {
var itemId = cartItemSnap.key();
//Get the inventory items from DB that are in the cart
var promise1 = ref.child('/inventory/' + itemId).once('value').then(function(inventoryItem) {
//Loop through booking IDs of inventoryItem
inventoryItem.child('rentals').forEach(function(rentalSnap) {
var rentalId = rentalSnap.key();
//Get bookings from rental/active
var promise2 = ref.child('/rental/'+ rentalId).once('value').then(function(activeRentals) {
console.log('check');
collector.push(promise2);
});
});
collector.push(promise1);
});
});
//Once everything was checked
Promise.all(collector).then(function() {
console.log('Done');
});
});
};
【问题讨论】:
-
checkIfBookingIsAllowed是做什么的?能否请您添加此代码? -
它检查日期重叠和项目的数量。这与我的问题并不相关。您可以简单地将这一行与 console.log('check');
-
使用
Promise.all():developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
@FrankvanPuffelen 感谢您的帮助。我试过了,检查我的新代码。我错过了什么?
-
您正在异步加载数据,因此需要确保您的承诺“冒泡”。在没有测试的情况下写答案有点棘手。您是否有机会在 jsbin 中重现该问题,以便我可以解决问题?
标签: javascript firebase promise firebase-realtime-database