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

259
Visualizações
http requests inside loop of variable size, how to do something only after last request has finished (JavaScript)

I'm using request to make HTTP requests inside a loop of variable size. (I will be reading words from a file, right now I just have an array). I'm adding onto an object (response) with each loop, and want to return the object only after the last request has been completed. I've been playing around with promises but I'm not sure how to chain them since it is a variable number of requests.

const request = require('request');

// eventually this array will be populated by reading a file
var words = ["hello", "there"];
var response = {};

// Loop thruogh input string
for (var i = 0; i < words.length; i += 1) {
    // get next word
    var curWord = words[i];
    // if the current word is not already in the response
    if (!(curWord in response)) {
        // request info from dictionary
        var options = {
            url: 'https://api.dictionaryapi.dev/api/v2/entries/en/' + curWord,
            json: true
        }
        request(options, (err, res, body) => {
            if (err) { return console.log(err); }            
            // find part of speech 
            var partOfSpeech;
            try {
                partOfSpeech = body[0].meanings[0].partOfSpeech
            } catch (err) {
                partOfSpeech = "undefined";
            }  
            // add to response          
            response[curWord] = partOfSpeech;
        });

    }
      
}
// do this part only after last request has been completed
console.log(response);

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Basically you need to count the responses knowing that when counter reaches zero you are done with them all.

EDIT: make sure you are referring the same curWord parameter in the response to match the request. This is done using the IIFE there.

I have setup an example for you

const request = function fake_request(options, callback) {
  setTimeout(function() {
    callback(null, options.url.slice(options.url.lastIndexOf('/')))
  }, Math.random() * 1000)
};

var words = ["hello", "there", "angela"];
var count = words.length;
var response = {}

for (var i = 0; i < words.length; i += 1) {
  var curWord = words[i];

  if (!(curWord in response)) {
    var options = {
      url: 'https://api.dictionaryapi.dev/api/v2/entries/en/' + curWord,
      json: true
    };

    (function(curWord) {

      request(options, (err, res, body) => {

        count--
        console.log(count)

        partOfSpeech = res;
        response[curWord] = partOfSpeech;

        if (count == 0) {
          // do this part only after last request has been completed
          console.log(response);
        }
      });

    })(curWord);
  }
}

about 4 years ago · Santiago Gelvez 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