Reputation: 531
I am having an issue where I want to send some requests to Plaid asking for account information, but when it's returned, I don't know where to associate the account information so I need to pass along an ID like source.id
. Problem is Promise.all
does not work with the way I've written things below. Is there another way to accomplish this so I can get back the ID I need?
var userSources = firestore.collection('sources');
userSources.get().then(snapshot => {
snapshot.forEach(doc => {
var source = doc.data();
sources.push(source);
});
return sources;
}).then((sources) => {
// 2: Connect to Plaid and query accounts
var promises = [];
sources.forEach(function(source) {
promises.push({
id: source.id,
p: client.getBalance(source.access_token)
});
});
return Promise.all(promises);
}).then...
```
Upvotes: 1
Views: 1118
Reputation: 707308
If you want to end up with an array if objects that have id
and balance
in them, you can do something like this. You call client.getBalance()
and in the .then()
handler you create the object you want in the result that combines source.id
with the balance
and you return that as the resolved value from the promise. You can then run Promise.all()
on that array of promises and get the appropriate array of objects as the result.
let userSources = firestore.collection('sources');
userSources.get().then(snapshot => {
return Promise.all(snapshot.map(doc => {
let source = doc.data();
return client.getBalance(source.access_token).then(balance => {
return {id: source.id, balance: balance};
});
}));
}).then(results => {
// array of {id, balance} objects
console.log(results);
});
This has an advantage that it puts the balance and corresponding id in the same array of objects rather than in separate arrays.
Upvotes: 3
Reputation: 370729
I'd consider using await
instead, so the sources
array in created in the upper part of the code, but is still visible to everything below it. Make sure the containing function is async, then:
const snapshot = await firestore.collection('sources').get();
const sources = snapshot.docs.map(doc => doc.data());
const promises = sources.map(source => client.getBalance(source.access_token));
const results = await Promise.all(promises);
// now, results[i] will correspond to sources[i].id
Note that you can use .map
to transform one array into another, which is a bit more appropriate than forEach
.
Upvotes: 1