I have this code in which I add users to the Firebase DB, and resolve the Promise when the user import is done. In the resolve, I include arrays which contain the users that were added. These arrays are populated when a single user is added. The code is below:
return new Promise((resolve, reject) => {
let usersAdded = [];
users.map((user, index) => {
db.ref('/users').push(user, err => {
if(!err) {
usersAdded.push(user)
console.log(`Array at iteration ${index}: ${usersAdded}`)
}
if(index == users.length-1){
resolve({status: true, usersAdded})
}
})
})
})
Console Output:
Array at iteration 0: [{name: nadir, email: [email protected], creditCard: true}]
Array at iteration 1: [{name: nadir, email: [email protected], creditCard: true}, {name: arslan, email: [email protected], creditCard: true}]
Array at iteration 2: [{name: nadir, email: [email protected], creditCard: true}, {name: arslan, email: [email protected], creditCard: true}, {name: farhan, email: [email protected], creditCard: true}]
Although when I see the response on .then(user), it returns an empty array (usersAdded). Users get added in Firebase as well. Can anyone tell me what is the problem here?
Edit:
I was able to solve it, the problem was that the Promise was resolved before the db.ref.push triggered the callback, in that callback, I was populating the array, as it was an async operation.
Promise.allon an array of Promises if you want to iterate over allusers?users. Not sure what you're intending here.ifstatement in which the condition is only true when the loop is on the last iteration.usersAddedarray, which ten will be send to the user usingres.send()db.ref...pushexecutes serially - otherwise, there's no guarantee that the last itempushis called with will be the last asynchronous operation to complete. Better to usePromise.all, though I'm not sure why theusersAddedresult would be empty, I'd expect it to contain at least one item (unless there was an error, in which case you might want toreject- also avoid the explicit Promise construction antipattern)