In node.js, I have an array of Promises but when I want to execute a Q.all().then(); process, It seems that nothing is happening. Maybe there is an unresolved promise in my array and it blocked the process ? I'm not really sure of what I'm doing here but my goal is to execute all this functions in one time and THEN get back my full "token" array to send it in another file.
How can I do that correctly with Q.all() ?
var pipo = new Array();
var ref_accounts = firebase.database().ref('accounts');
geoQuery.on("key_entered", function(lakey, location, distance) {
pipo[lakey] = lakey;
});
// I have here my pipo Array full of data
var promises = [];
var token = [];
for (var key in pipo) {
var deferred = Q.defer();
var ref = firebase.database().ref("etablissements").orderByKey().equalTo(value).on("child_added", function(snapshot) {
var data = snapshot.val();
if ((data.alerte != false) && (data.categorie === categories)) {
var ref2 = firebase.database().ref("accounts").orderByKey().equalTo(value).on("child_added", function(snapshot2) {
var data2 = snapshot2.val();
if (data2.token != null) {
token.push(data2.token);
deferred.resolve(data2);
} else {
deferred.reject();
// or deferred.resolve(); ??
}
});
} else {
deferred.reject();
// or deferred.resolve(); ??
}
});
promises.push(deferred.promise);
}
I have my "promises" array full and Now I want here to execute all in once and THEN get all the TOKEN caught in the array
Q.all(promises).then(function(results) {
var uniqueNames = [];
for (i = 0; i < token.length; i++) {
if (uniqueNames.indexOf(token[i]) === -1) {
uniqueNames.push(token[i]);
console.log('tokens' + token[i]);
}
},
// error
function(response) {
console.log('Error in then' + response);
}).catch(function(error) {
console.log('CATCH ERROR' + error);
});
// Send token array to the API
});
I really don't understand the process. Can you explain me what's wrong with this code please ?