-2

How do I execute a HTTP request synchronously and store the result in a local object with Javascript?

Given the following javascript module:

var Promise = require("promise");                                                                                                                                                                       

function myReq(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.responseType = 'json';
    xhr.onload = () => {
      if (xhr.status >= 400){
        console.log("got rejected");
        reject({status: xhr.status, statusText: xhr.statusText});
      } else {
        console.log("resolved");
        resolve({data: xhr.response});
      }
    };
    xhr.onerror = () => {
      console.log("Error was called");
      reject({status: xhr.status, statusText: xhr.statusText});
    };
    xhr.send();
  });
}

export default myReq;

I want the json object from this request stored in a local variable in another script. However, when I try this code it runs it async.

1. import myReq from '../../lib/myReq';
2. const urlTest = "localhost://3000:/somepath";
3. const test = myReq(urlTest).then((a) => {console.log(a); return a;}).catch((b) => console.log(b));
4. console.log(test.data);

I want it to stop at line 3, execute the code, store the javascript object in test, and the resume execution of the rest of the code. Right now test is a Promise and test.data is undefined.

Alexander R Johansen
  • 2,737
  • 3
  • 18
  • 23

2 Answers2

1

myReq returns a Promise, NOT just the data! That is why you need to use then & catch blocks, or alternatively use await.

// myReq function returns a Promise, NOT a value! (Not returning 5!)
function myReq(url) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(5);
    }, 5000);
  });
}

// Option 1
myReq('someurl').then((data) => {
  console.log('data (option 1)', data); // You can use the data here, inside the 'then' block
}).catch((error) => {
  console.log('error', error);
});

// Option 2
const run = async () => {
  try {
    const data = await myReq('someurl'); // await must be called from an 'async' function
    console.log('data (option 2)', data); // You can use the data here, inside the 'try' block
  } catch (error) {
    console.log('error', error);
  }
};
run();
Ron Hillel
  • 160
  • 6
0

If you want to convert this to a synchronous process you can directly use the async/await to handle the process rather than directly moving to next step. Like you can do something like:

try {
const result = await myReq(url);
} catch (e) {
 // Handle error generated in the process
}

remember you can only async/await in pair means that only inside an async function you can use await keyword. For more details you can visit this article

Hope this helps. Have a good day.

kshitij
  • 642
  • 9
  • 17