Home > database >  How does one access, process and pass along response data outside of the request?
How does one access, process and pass along response data outside of the request?

Time:10-13

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: []

CodePudding user response:

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

CodePudding user response:

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);
  • Related