如何使用 api 调用结果的值创建对象?

问题描述 投票:0回答:1

晚上好,

我目前正在尝试创建一个包含以下内容的对象:

{
  "acct_123": [
   // result from calling stripe api 
  ],
  "acct_456": [
   // result from calling stripe api 
  ]
}

我的函数的参数是stripeIds列表:

['acct_123', 'acct_456']

我试过这个:

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);

不幸的是,此调用仅获取数组中第一个元素的数据。 :|

您能帮我设置对象键 id 和 fetchList(id) 结果的值吗?

谢谢! :)

javascript arrays typescript api dictionary
1个回答
0
投票

您的获取列表功能

   const fetchList = async (id) =>
     (await stripe.accounts.listExternalAccounts(
       id, { object: "bank_account" })).data;

将 id 映射到 Promise

let fetchPromises = stripeAccountIds.map(id =>
  fetchList(id).then(data => ({ id, data })));

一旦所有 Promise 解析结果将是一个 ids 和相应数据的数组

  const results = await Promise.all(fetchPromises);

构造结果对象

   let resultObject = results.reduce((acc, { id, data }) =>
           ({ ...acc, [id]: data }), {});

将所有内容放在一起。

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));
© www.soinside.com 2019 - 2024. All rights reserved.