I need to be able to map (or if need be, foreach) over an array of accounts. I want to verify whether or not the account exists in Firebase Firestore before I either update it or add it as a new account. The problem is that the map keeps running and then the Firebase Firestore function finally run. I tried wrapping the Firestore in its own promise but it didn't work. I need everything to run in order. I know my Promise and/or Async/Await are in the wrong places. I'm still learning how to properly use promises and async/await.
let db = admin.firestore();
(async () => {
const accountInfo = [{ accountNumber: 'a' }, { accountNumber: 'b' }, { accountNumber: 'c' }];
for (let i = 0, j = accountInfo.length; i < j; i++) {
console.log("i: ", i);
await Promise.all(
accountInfo
.map(account => {
const {accountNumber} = account;
console.log(accountNumber);
// Firebase - Firestore
let docRef = db.collection('accounts').doc(accountNumber);
docRef.get().then(function (doc) {
console.log("doc.exists ", doc.exists)
if (doc.exists) {
firebaseUpate();
}
else {
firebaseAdd();
}
})
})
)
}
})();
The results I'm getting:
[0] i: 0
[0] a
[0] b
[0] c
[0] i: 1
[0] a
[0] b
[0] c
[0] i: 2
[0] a
[0] b
[0] c
[0] doc.exists false
[0] doc.exists false
[0] doc.exists false
[0] doc.exists false
[0] doc.exists false
[0] doc.exists false
[0] doc.exists false
[0] doc.exists false
[0] doc.exists false
The results I need: Console.log()
[0] i: 0
[0] a
[0] doc.exists false
[0] i: 1
[0] b
[0] doc.exists false
[0] i: 2
[0] c
[0] doc.exists false