求助:如何创建键为Stripe ID、值为API调用结果的对象?
问题分析与解决方案
原代码存在的问题
obj未初始化,直接赋值obj[id]会导致运行时错误或无有效结果- 使用
map搭配async/await时,未正确收集异步操作的Promise,Promise.all执行时Promise数组可能还未被填满 - 未等待
Promise.all完成,无法保证所有异步请求处理完毕
正确实现方式
方案一:简洁版(利用Object.fromEntries)
const fetchList = async (id: string) => { const resp = await stripe.accounts.listExternalAccounts( id, { object: "bank_account" }, { apiKey } ); return resp.data; }; const getBankAccountsMap = async (stripeConnectAccountIds: string[]) => { // 生成[id, 对应异步结果]的Promise数组 const promiseEntries = stripeConnectAccountIds.map(async (id) => [ id, await fetchList(id) ]); // 等待所有请求完成,得到[[id1, data1], [id2, data2]]结构 const resolvedEntries = await Promise.all(promiseEntries); // 转换为目标键值对对象 return Object.fromEntries(resolvedEntries); }; // 使用示例 // getBankAccountsMap(['acct_123', 'acct_456']).then(result => console.log(result));
方案二:手动遍历版(适合需要中间处理的场景)
const fetchList = async (id: string) => { const resp = await stripe.accounts.listExternalAccounts( id, { object: "bank_account" }, { apiKey } ); return resp.data; }; const getBankAccountsMap = async (stripeConnectAccountIds: string[]) => { // 初始化目标对象 const bankAccountsObj: Record<string, any[]> = {}; const promises: Promise<void>[] = []; for (const id of stripeConnectAccountIds) { // 封装每个异步任务并收集Promise const task = async () => { bankAccountsObj[id] = await fetchList(id); }; promises.push(task()); } // 等待所有异步任务完成 await Promise.all(promises); return bankAccountsObj; }; // 使用示例 // getBankAccountsMap(['acct_123', 'acct_456']).then(result => console.log(result));
原代码仅获取第一个元素的原因
原代码中map的异步回调会延迟执行,而Promise.all在map遍历完成后立即执行,此时bankAccoutFetchPromises数组还未被填充完整;同时obj未初始化,导致最终无法正确存储所有请求结果。
内容的提问来源于stack exchange,提问作者Carmen Mitru
相关产品推荐
相关产品推荐

