0
function request2API(option){
    const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2
const request = new XMLHttpRequest();
request.open('GET',  urlStart + ChList[option].videosList + keyPrefix + key);
request.send();
request.onload = ()=> {
    if(request.status === 200){
        const response = JSON.parse(request.response);
        console.log(response) //At this point the Object respond exists
        return response;
    };
};
};

let indexChannel = inputFunction("\n Pick an option ")
let fetchedData = request2API(indexChannel); //By this point it has died
console.log(fetchedData);

I've tried to assign the fetched data to a variable as one would do in regular JavaScript for a browser but it's not working.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
axkels
  • 1

1 Answers1

-2

Maybe try:

function request2API(option){
  const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2
  const request = new XMLHttpRequest();
  request.open('GET',  urlStart + ChList[option].videosList + keyPrefix + key);
  request.send();
  request.onload = ()=> {
      if(request.status === 200){
          const response = JSON.parse(request.response);
          console.log(response) //At this point the Object respond exists
          return response;
      };
  };
};

async function() {
let indexChannel = inputFunction("\n Pick an option ")
let fetchedData = await request2API(indexChannel); //By this point it has died
console.log(fetchedData);
}
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
  • 1
    You're using `await request2API()`, but the `await` is pointless since `request2API()` does not return a promise that is connected with when it completes. `await` is ONLY useful when you are awaiting a promise that fulfills when the underlying operation is complete. `request2API()` has no return value at all. The `return response` is inside an asynchronous callback, and `request2API()` has already long since returned. To use promises here, it would be a lot easier to just use `fetch()` which is already promise-based. – jfriend00 Dec 10 '22 at 05:13
  • I totally agree. – Ronnie Royston Dec 10 '22 at 14:16