Good evening,
I am currently trying to create an object that will contain:
{
"acct_123": [
// result from calling stripe api
],
"acct_456": [
// result from calling stripe api
]
}
The parameter of my function is the list of stripeIds: ['acct_123', 'acct_456']
I tried this:
const fetchList = async (id: string) => {
const resp = await stripe.accounts.listExternalAccounts(
id,
{ object: "bank_account" },
{ apiKey }
)
return resp.data;
}
let bankAccoutFetchPromises: any = [];
let obj;
stripeConnectAccountIds.map(async (id: string) => {
const bankAccountList = await stripe.accounts.listExternalAccounts(
id,
{ object: "bank_account" },
{ apiKey }
);
obj[id] = bankAccountList.data;
bankAccoutFetchPromises.push(bankAccountList.data);
});
Promise.all(bankAccoutFetchPromises);
Unfortunately this call only fetch the data for the first element in the array. :|
Can you please help me with setting object key the id and the value the result from fetchList(id)?
Thanks! :)
your fetch list function
const fetchList = async (id) =>
(await stripe.accounts.listExternalAccounts(
id, { object: "bank_account" })).data;
map ids to promises
let fetchPromises = stripeAccountIds.map(id =>
fetchList(id).then(data => ({ id, data })));
once all promises resolve results will be an array of ids and corresponding data
const results = await Promise.all(fetchPromises);
construct the result object
let resultObject = results.reduce((acc, { id, data }) =>
({ ...acc, [id]: data }), {});
putting it all together.
const stripe = require('stripe')('your_stripe_secret_key');
const fetchList = async (id) =>
(await stripe.accounts.listExternalAccounts(id, { object: "bank_account" })).data;
async function fetchAllAccounts(stripeAccountIds) {
let fetchPromises = stripeAccountIds.map(id =>
fetchList(id).then(data => ({ id, data }))
);
const results = await Promise.all(fetchPromises);
let resultObject = results.reduce((acc, { id, data }) =>
({ ...acc, [id]: data }), {}
);
return resultObject;
}
// Example usage:
const stripeConnectAccountIds = ['acct_123', 'acct_456'];
fetchAllAccounts(stripeConnectAccountIds).then(result => console.log(result));