You need to enable JavaScript to run this app. Node.js中Promise.all未等待then执行完成就触发res.json返回的问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中Promise.all未等待then执行完成就触发res.json返回的问题求助

问题描述

首先我是Node.js新手,还请多多包容:)

我在处理异步函数时遇到了问题:先发起一次API调用,再对返回的每个条目发起子调用,第一次调用完成后的代码如下:

const countryStatesCalls: Promise<any>[] = [];
countries.forEach((country, index) => {
  countries[index] = convertToCountry(country);
  const countryStatesCall = (countryId: number) => {
    return new Promise((resolve, reject) => {
      const countryStatesList = getStateCountries(countryId);
      if (countryStatesList) {
        if (Object.prototype.toString.call(countryStatesList) !== '[object Array]') {
          resolve([]);
        } else {
          resolve(countryStatesList);
        }
      } else {
        reject([]);
      }
    });
  };
  countryStatesCalls.push(
    countryStatesCall(countries[index].id).then(countryStates => {
      countries[index].states = countryStates;
    }).catch(countryStatesType => {
      countries[index].states = countryStatesType;
    })
  );
});

await Promise.all(countryStatesCalls).then(_ => {
  res.json(countries)
});

以下代码

res.json(countries)

本应在所有Promise执行完毕后才执行,但实际提前触发了。

补充:getStateCountries async函数实现如下:

const getStateCountries = async (countryId: number, lang?: string) => {
const listState = await odoo.searchRead(
  'res.country.state',
  {
    filters: [
      {
        field: 'country_id',
        operator: '=',
        value: countryId,
      },
    ],
    fields: fieldState,
  },
  { lang }
);

if (!listState.length) {
  return [];
} else {
  listState.forEach((state, index) => {
      listState[index] = convertToState(state);
  });
  return listState;
}

主函数是一个Express控制器,我认为我的错误可能比较明显,但查阅了很多相关资料仍然找不到问题所在,恳请大家帮忙,谢谢。

问题原因

自定义封装的countryStatesCall Promise中,直接同步调用了异步函数getStateCountries,没有等待它的异步返回就直接做了值判断:getStateCountries是async函数,调用后会直接返回Promise实例,所以同步判断countryStatesList永远为真,整个外层Promise会立即resolve,不会等待实际的接口请求完成,最终导致Promise.all提前执行完成,res.json提前触发。

解决方案

修正后不再做多余的Promise封装,直接收集getStateCountries的返回Promise实例,统一等待所有请求完成后再批量赋值返回:

const countryStatesCalls: Promise<any>[] = [];
for (let index = 0; index < countries.length; index++) {
  countries[index] = convertToCountry(countries[index]);
  if (withSates) {
    countryStatesCalls.push(
      getStateCountries(countries[index].id)
    );
  } else {
    countries[index].states = [];
  }
}

if (withSates) {
  await Promise.all(countryStatesCalls).then((countriesStates) => {
    countries.forEach((country, index) => {
      country.states = [];
      for (const countryStates of countriesStates) {
        if (countryStates.length
          && countryStates[0].country_id.code === country.id) {
          countries[index].states = countryStates;
        }
      }
    });
    res.json(countries);
  });
} else {
  res.json(countries);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 01:09:03