You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中将多个Promise返回的数组合并为单个数组

解决Promise多轮异步请求结果合并问题

我现在用Promise异步获取数据,流程是:

  • 遍历每个公司ID获取支付信息
  • 遍历每个支付ID获取雇主信息
  • 将所有雇主信息合并为单个数组

但现有代码执行后得到3个独立的雇主信息数组,没法合并成预期的单个数组,附上代码、返回示例及预期结果,求解决方法。


原代码

var data =  [
                {
                    id: 1,
                    company: 'A'
                },
                {
                    id: 2,
                    company: 'B'
                },
                {
                    id: 3,
                    company: 'C'
                }
            ]

var p1 = [];
for(var i =0; i < data.length; i++){
  p1.push(global.get_payments(data, i));
}
Promise.all(p1)
.then(response_p1 => {
    // 以下是response_p1的结构
    for(var i =0; i < response_p1.length; i++){
        var employers = [];
        for(var x =0; x < response_p1[i].payment.length; x++){
            employers.push(global.get_employers(response_p1[i].payment, x));
        }
        Promise.all(employers)
        .then(response_employers => {
            // 如何把所有response_employers合并成一个数组?
        }).catch(err => {
            console.log(err)
        })
    }
}).catch(err => {
  console.log(err)
})

返回示例与预期结果

现有返回结果

response_p1:

[
    {
        id: 1,
        company: 'A',
        payment: [{id: 4}]
    },
    {
        id: 2,
        company: 'B',
        payment: [{id: 5}]
    },
    {
        id: 3,
        company: 'C',
        payment: [{id: 6}]
    }
]

response_employers(三个独立数组):

[
    {
        id: 4,
        employer_list: [
            {id: 1, name: 'Carles'},
            {id: 2, name: 'Max'}
        ]
    }
]
[
    {
        id: 5,
        employer_list: [
            {id: 3, name: 'Dania'},
            {id: 4, name: 'Luis'}
        ]
    }
]
[
    {
        id: 6,
        employer_list: [
            {id: 5, name: 'Lenny'},
            {id: 6, name: 'Hommer'}
        ]
    }
]

预期结果

[
    {
        id: 4,
        employer_list: [
            {id: 1, name: 'Carles'},
            {id: 2, name: 'Max'}
        ]
    },
    {
        id: 5,
        employer_list: [
            {id: 3, name: 'Dania'},
            {id: 4, name: 'Luis'}
        ]
    },
    {
        id: 6,
        employer_list: [
            {id: 5, name: 'Lenny'},
            {id: 6, name: 'Hommer'}
        ]
    }
]

解决方案

问题分析

  • 原代码在遍历response_p1时,每次单独执行Promise.all(employers),没有统一收集这些Promise并等待全部完成,导致无法一次性合并所有结果。
  • 使用var会引发循环变量作用域问题,建议替换为let/const避免意外错误。

修正后的代码

const data = [
    { id: 1, company: 'A' },
    { id: 2, company: 'B' },
    { id: 3, company: 'C' }
];

// 第一步:获取所有公司的支付信息
const paymentPromises = data.map((item, index) => global.get_payments(data, index));

Promise.all(paymentPromises)
.then(response_p1 => {
    // 提取所有支付项并合并为一维数组
    const allPayments = response_p1.flatMap(company => company.payment);
    // 第二步:为每个支付项创建获取雇主信息的Promise
    const employerPromises = allPayments.map((payment, index) => global.get_employers(allPayments, index));
    
    // 等待所有雇主信息请求完成
    return Promise.all(employerPromises);
})
.then(allEmployerResponses => {
    // 扁平化结果:将嵌套数组转为一维数组,得到预期格式
    const finalResult = allEmployerResponses.flat();
    console.log(finalResult);
})
.catch(err => {
    console.error('请求出错:', err);
});

代码说明

  1. 用map替代for循环收集Promise,代码更简洁易读。
  2. 使用flatMap直接从response_p1中提取并合并所有支付项,避免嵌套循环。
  3. 统一收集所有获取雇主信息的Promise,通过Promise.all等待全部完成后,用flat()将嵌套数组合并为一维数组,直接得到预期结果。

内容的提问来源于stack exchange,提问作者Dimoreno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:06:28