How to call methods one after one?

Viewed 174

There is a function that accepts three parameters:

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

}

I need to create a promise that returns data for each varaible and as result returns a common object {countries: [], cities: [], regions: []}

How to do that using promise(s)?

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

If you have three different end points that are not dependent on each other then u can use this approach:

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);
            })

What you want to achieve , you can use callback function to achieve these behavior without using promise.

async function getAddressStructure(country(args, getCities,getregioR)
{
    var countries = await getCountries():
    var cities= await getCities ():
    var regions = await  getRegion ();

    return { countries : countries, cities: cities, regions: regions}
}

async function getCountries ();
async function getCities() {}
async function getRegion () {}
Related