如何一一调用方法?

2024-04-09

有一个函数接受三个参数:

function getAddressStructure(country: number, city: number, region: number) {

}

我需要创建一个承诺,返回每个变量的数据,并作为结果返回一个公共对象{countries: [], cities: [], regions: []}

如何使用承诺来做到这一点?

let promise = new Promise((resolve, reject) => resolve());

如果您有三个不同的端点,并且彼此不依赖,那么您可以使用此方法:

export async function handleResponse(response) {
  if (response.ok) return response.json();
  if (response.status === 400) {
    const error = await response.text();
    throw new Error(error);
  }
  throw new Error("Network response was not ok.");
}

export function handleError(error) {
  console.error("API failed. " + error);
  throw error;
}


export function GetCountries() {
  const url = "/countries"
  return fetch(url, {
    method: "GET",
    credentials: "include",
  }).then(handleResponse).catch(handleError);
}

export function GetCities() {
  const url = "/cities"
  return fetch(url, {
    method: "GET",
    credentials: "include",
  }).then(handleResponse).catch(handleError);
}

export function GetRegions() {
  const url = "/regions"
  return fetch(url, {
    method: "GET",
    credentials: "include",
  }).then(handleResponse).catch(handleError);
}

function getAddressStructure() {
  return Promise.all([
    GetCountries(),
    GetCities(),
    GetRegions()
  ])
    .then((response) => {
      return {
        countries: response[0],
        cities: response[1],
        regions: response[2]
      };
    })
    .catch((error) => {
      return {
        countries: response[],
        cities: response[],
        regions: response[]
      }
    });
}


// this is how you can use it:
          getAddressStructure()
            .then((response) => {
              var apiResults = { };
              apiResults = { ...response};
              return resolve(apiResults);
            })

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何一一调用方法? 的相关文章

随机推荐