I was having some problem with JavaScript promises. Here is my code:
let promiseDataList = new Promise((resolve, reject) => {
// first query to get list of all receipt items under certain category
var query = firebase.database().ref('receiptItemIDsByCategory').child(category);
query.once( 'value', data => {
// promises array
var promises = [];
// loop through each and get the key for each receipt items
data.forEach(snapshot => {
var itemData = snapshot.val();
// get key here
var itemKey = snapshot.key;
// second query to get the details of each receipt items based on the receipt item key
var query = firebase.database().ref('receiptItems').child(itemKey);
var promise = query.once('value');
promises.push(promise);
promise.then(data => {
// get receipt item details based on the item key
var itemDetail = data.val();
var price = itemDetail.price;
var quantity = itemDetail.quantity;
var itemTotal = price * quantity;
var receiptID = itemDetail.receiptID;
// get branch details based on receipt ID
var query = firebase.database().ref('receipts');
var promise1 = query.once('value');
// add promise to array
promises.push(promise1);
// find matching receiptID then get its branch details
promise1.then(data => {
data.forEach(snapshot => {
snapshot.forEach(childSnapshot => {
if(childSnapshot.key == receiptID){
var branchDetail = childSnapshot.val().branch;
var branchName = branchDetail.branchName;
var branchAddress = branchDetail.branchAddress;
console.log(branchName + ' ' + branchAddress + ' ' + itemTotal);
// push data into the final array to be used in some other parts
datasetarr.push({branchName: branchName, branchAddress: branchAddress, total: itemTotal});
}
});
});
});
});
});
// wait till all promises are finished then resolve the result array
Promise.all(promises).then(() => resolve(datasetarr));
});
});
promiseDataList.then((arr) => {
console.log('promise done');
for(var i = 0; i < arr.length; i++){
console.log(arr[i].branchName + ' ' + arr[i].branchAddress + ' ' + arr[i].total);
}
});
I have added some comments to explain what I am trying to do. The problem now is at the point where I get the receiptID
and created another promise variable
and push it into promise array, the console.log
there is printing out the result.
However, after I commented out that line and tried to print out the result at the .then()
, the promise done message is printed out but there is no result from the array, nor error message, which mean the asynchronous execution is not done properly.
Any ideas how to fix this?