I was having some problem with promise in JavaScript. So what I am trying to do is I wanted to retrieve from firebase, then store all the result returned into array. After that I will perform some sorting on the array. Here is my code:
let promise = new Promise((resolve, reject) => {
var query = firebase.database().ref('');
query.once( 'value', data => {
data.forEach(subtypeSnapshot => {
var itemData = ;
var query = firebase.database().ref('').child(itemKey);
query.once( 'value', data => {
var itemDetail = ;
datasetarr.push();
});
});
resolve(datasetarr);
});
});
With this set of code, from the first console.log
inside the promise, I managed to get these in my console:
With these, it means there is nothing wrong with my firebase retrieval. Afterwhich, I wanted to store each of them into array and this is the part:
datasetarr.push({type: subtype, quantity: quantity});
After done everything and I resolved the promise, when promise is done, I then print out the items in array. However, nothing is printed out at the for loop inside .then()
. Any ideas?
Your first
async
call for retrieving the initial set of data was handled correctly but not the subsequent ones invoked by the.forEach
loop.Trouble is you're
resolving
the promise before the other async call was returned.I'm not sure how exactly is
query.once
handlingcallback
. It doesn't look like it is doing promises nor the traditionalcallback function
way.What you could do as a
work-around
is to wrap theforEach.async
calls into aPromise
object and then fire a collection of promises usingPromise.all([list_of_promises])
to make sure that every single call was returned beforeresolving
the main promise.Pseudo code:
As already mentioned: Your Promise is resolved too early.
You can use Promise.all to wait for all promises to resolve before resolving the wrapping Promise. I put together a simple example, however, because of the lack of a firebase database, I just use functions returning Promises: https://jsfiddle.net/57b0gkLt/
According to the firebase documentation,
query.once('value')
returns a Promise, so this should work.EDIT: Like this