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

如何在JavaScript中等待API调用完成(map+setTimeout场景)

解决方案:等待带延迟的API调用全部完成

你的代码问题在于setTimeout是传统回调式异步操作,没有被包装成Promise,导致Promise.all无法追踪到延迟后执行的API调用,所以提前输出了完成日志。要解决这个问题,需要把setTimeout封装成Promise,让整个延迟+API调用的流程成为可被等待的异步任务。

修改后的完整代码:

async function FieldMapping() {
    let data = [
        {
            "contractID": "D3047-IND-001",
            "fieldValues": {
                "custrecord_vgicp_add_insurance_expense": "3000",
                "custrecord_vgicp_advancespaid": "2000",
                "custrecord_vgicp_allow_food_other": "3000"
            }
        },
        {
            "contractID": "D3048-IND-003",
            "fieldValues": {
                "custrecord_vgicp_add_insurance_expense": "3700",
                "custrecord_vgicp_advancespaid": "3700",
                "custrecord_vgicp_allow_food_other": "3700"
            }
        },
        {
            "contractID": "D3049-IND-001",
            "fieldValues": {
                "custrecord_vgicp_add_insurance_expense": "3700",
                "custrecord_vgicp_advancespaid": "3700",
                "custrecord_vgicp_allow_food_other": "3700"
            }
        },
        {
            "contractID": "D3081-FRA-002",
            "fieldValues": {
                "custrecord_vgicp_add_insurance_expense": "3700",
                "custrecord_vgicp_advancespaid": "3700",
                "custrecord_vgicp_allow_food_other": "3700"
            }
        },
        {
            "contractID": "D3106-IND-002",
            "fieldValues": {
                "custrecord_vgicp_add_insurance_expense": "2000",
                "custrecord_vgicp_advancespaid": "2000",
                "custrecord_vgicp_allow_food_other": "2000"
            }
        }
    ];

    // 封装setTimeout为Promise
    const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

    await Promise.all(data.map(async (payroll, index) => {
        // 等待指定延迟
        await delay(1000 * index + 1);
        // 执行API调用并等待结果
        let result = await apiCall(payroll);
        console.log("result:::", result);
    }));

    console.log("All API Action completed...");
}

async function apiCall(payroll) {
    // 实际API调用逻辑,示例返回传入的contractID
    return Promise.resolve(payroll.contractID);
}

关键修改说明:

  • 新增delay函数,把setTimeout包装成返回Promise的异步操作,这样可以用await等待延迟结束
  • 移除原代码中嵌套的setTimeout回调,改为先await delay(...),再执行API调用,确保整个流程被Promise.all正确追踪
  • 修正apiCall函数参数,原代码中没有接收payroll参数,这里补上以符合逻辑

这样修改后,Promise.all会等待所有带延迟的API调用全部完成,才会执行后续的"All API Action completed..."日志输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:15:33