Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
NodeJS: Chain functions automatically in a promise?

I'm currently fetching data from an API and I need to do multiple GET requests (using axios). After all those GET requests are completed, I return a resolved promise.

However, I need to do these GET requests automatically based on an array list:

    function do_api_get_requests() {

        return promise = new Promise(function(resolve, reject) {

          API_IDs = [0, 1, 2];

          axios.get('https://my.api.com/' + API_IDs[0])
          .then(data => {
            // Do something with data

            axios.get('https://my.api.com/' + API_IDs[1])
            .then(data => {
              // Do something with data

              axios.get('https://my.api.com/' + API_IDs[2])
              .then(data => {
                // Do something with data
                
                // Finished, resolve
                resolve("success");
                
              }


            }


          }

        }

    }

This works but the problem is API_IDs isn't always going to be the same array, it will change. So I'm not sure how to chain these requests automatically.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Since you said it can be a variable length array and it shows the sequence of the requests, you can iterate through the array using async/await:

 async function do_api_get_requests(API_IDS) { for (let id of API_IDS) { const data = await axios.get(`https://my.api.com/${id}`); // do something with data here } return "success"; }

And since you said the list of API IDs would be variable, I made it a parameter that you can pass to the function.


If you want to run all API requests in parallel (which might be fine for a small array, but might be problematic for a large array) and you don't need to run them in any specific order, you can do this:

 function do_api_get_requests(API_IDS) { return Promise.all(API_IDS.map(async (id) => { const data = await axios.get(`https://my.api.com/${id}`); // do something with data here for this request })).then(() => { // make resolved value be "success" return "success"; }); }

Depending on your circumstances, you could also use Promise.allSettled() . Since it doesn't show getting results, it's not clear if it would be useful or not.

over 4 years ago · Santiago Trujillo Relatório

0

You can use Promise.all() method to do all API requests at the same time, and resolve when all of them resolves.

function do_api_get_requests() {
  const API_IDs = [0, 1, 2];

  let promises = [];
  for (const id of API_IDS) {
    promises.push(axios.get(`https://my.api.com/${id}`));
  }

  return Promise.all(promises);
}
over 4 years ago · Santiago Trujillo Relatório

0

If you use Bluebird.js (a better promise library, and faster than the in-built Promise), you can use Promise.each(), Promise.mapSeries(), or Promisme.reduce() to do what you want.

http://bluebirdjs.com

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda