如何访问、处理和传递请求之外的响应数据?

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

在下面的代码片段中,我希望能够在请求函数之外访问 locationArray,我明白在下面的代码中为什么它不起作用,但是,我尝试了许多不同的方法来访问数组。我尝试过使用承诺、回调函数等,但是,none 似乎有效。

关于如何做到这一点还有其他想法吗?甚至对我尝试过的方式持开放态度,因为在这一点上一切都值得一试。

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

@StackSlave 是对的,它只需要一个承诺,我相信我第一次尝试使用承诺解决它时搞砸了语法,但这似乎有效。

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

人们不仅可以考虑基于 Promise 的方法,因为它已经被建议,而且还可以考虑代码重构,将不同的关注点分离到任务中,并将后者实现为函数,可以是 fed/passed 到承诺链。作为一个优势,重构以人类可读的代码作为回报,这也可能更容易维护 ...

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