Reputation: 3740
I need to send a few requests to the DB and update each entry from the response.
I am trying to use forEach/for but as far as forEach/for is async I can't find a way how to do a few requests to Firebase DB using cycle.
Any ideas?
Here is my code. I've tried to do work around with counter inside the cycle. But unfortunately, this not works for me.
function updateMethod(inputArray) {
return new Promise((resolve, reject) => {
var updates = {};
var ctr = 0;
for (let i = 0; i < inputArray.length; i++) {
db.ref("/foo").orderByChild("finished").equalTo(inputArray[i]).once("value", (snapshot) => {
ctr++;
var key = snapshot.key;
updates['transactions/' + key + '/finished'] = true;
if (ctr === inputArray.length) {
resolve(updates);
}
}).catch((e) => {
console.log(e);
});
}
});
}
So bottom line: I need to do a few requests inside cycle and then make a return from the method.
Upvotes: 0
Views: 38
Reputation: 2688
You can update your code to push into a list of promises and wait for all promises to complete, an example would be;
function updateMethod(inputArray) {
var promises = [];
var updates = {};
var ctr = 0;
for (let i = 0; i < inputArray.length; i++) {
var promise = db.ref("/foo")
.orderByChild("finished")
.equalTo(inputArray[i])
.once("value", (snapshot) => {
var key = snapshot.key;
updates['transactions/' + key + '/finished'] = true;
}).catch((e) => {
console.log(e);
});
promises.push(promise);
}
return Promise.all(promises);
}
Upvotes: 1
Reputation: 317487
Don't pass a callback to once(), use its returned promise instead.
Collect all the promises returned by each call to once() into an array, then pass that to Promise.all() to create a new promise that's resolved when all the other promises are resolved. You can return that, or do further processing on the snapshots and return a different Promise that resolves with the final value you want the caller to have.
Upvotes: 1