Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
How does one access, process and pass along response data outside of the request?

In the snippet below, I want to be able to access locationArray outside of the request function, I understand that in my code below why it will not work, however, I have tried many different methods to access the array. I have tried using promises, callback functions etc, however, none of them seem to be working.

Any other ideas on how to do this? Even open to ways I've tried as at this point everything is worth a try.

request(process.env.RESOURCE_SHEET, (error, response, html) => {
   var locationArray = new Array
      if(!error && response.statusCode == 200) {
  
      const $ = cheerio.load(html);
              
       $("h3").each((i, lle) => {
        const location = $(lle).text();
  
        if(location.includes("Kansas")) return;
        if(location.includes("In Stock")) {
           var level = location + " ✅";
        } else {
           var level = location + " ❌";
        }
        locationArray.push(level);
        });
       } 
       console.log(locationArray) // Output 1: [level1,level2,level3,leveletc]
});
console.log(locationArray) // Output 2: []
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

@StackSlave was right, it just needed a promise, I believe I messed up the syntaxing when I first tried resolving it using a promise, but this seemed to work.

const promise = new Promise((resolve,reject) => {
 request(process.env.RESOURCE_SHEET, (error, response, html) => {
   var locationArray = new Array
      if(!error && response.statusCode == 200) {
  
      const $ = cheerio.load(html);
              
       $("h3").each((i, lle) => {
        const location = $(lle).text();
  
        if(location.includes("Kansas")) return;
        if(location.includes("In Stock")) {
           var level = location + " ✅";
        } else {
           var level = location + " ❌";
        }
        locationArray.push(level);
        resolve(locationArray);
        });
       } 
       console.log(locationArray) // Output 1: [level1,level2,level3,leveletc]
 });
});
promise.then(array => {
  console.log(array);
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

One not only might consider a Promise based approach, as it got already suggested, but also a code refactoring which separates the different concerns into tasks and implements the latter as functions which can be fed/passed to the promise chain. As an advantage the refactoring pays back with human readable code which also might be easier to maintain ...

function createRequest(src) {
  return new Promise((resolve, reject) => {

    request(src, (error, response, html) => {
      if (!error && response.statusCode === 200) {

        resolve(html);
      } else {
        reject({ error, response });
      }
    });
  };
}
function handleFailedRequest(reason) {
  const { error, response } = reason;
  // proceed with failure handling based on
  // either request data `error` and/or `response`.
}

function createLocationArray(html) {
  const locationArray = [];
  const $ = cheerio.load(html);

  $('h3').each((i, lle) => {
    const location = $(lle).text();
    if (!location.includes('Kansas')) {

      const isInStock = location.includes('In Stock');
      locationArray.push(
        `${ location } ${ isInStock && '✅' || '❌' }`
      );
    }
  });
  return locationArray;
}
function processLocationArray(array) {
  console.log('locationArray ... ', array);
}

const promisedResponse = createRequest(process.env.RESOURCE_SHEET);

promisedResponse
  .then(createLocationArray)
  .then(processLocationArray)
  .catch(handleFailedRequest);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda