Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

248
Views
solicitudes http dentro del ciclo de tamaño variable, cómo hacer algo solo después de que finalice la última solicitud (JavaScript)

Estoy usando request para realizar solicitudes HTTP dentro de un bucle de tamaño variable. (Estaré leyendo palabras de un archivo, en este momento solo tengo una matriz). Estoy agregando un objeto (respuesta) con cada bucle y quiero devolver el objeto solo después de que se haya completado la última solicitud. He estado jugando con las promesas, pero no estoy seguro de cómo encadenarlas, ya que es un número variable de solicitudes.

 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 answers
Answer question

0

Básicamente, debe contar las respuestas sabiendo que cuando el contador llegue a cero, habrá terminado con todas.

EDITAR: asegúrese de referirse al mismo parámetro curWord en la respuesta para que coincida con la solicitud. Esto se hace usando el IIFE allí.

He configurado un ejemplo para ti.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!