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.
CodePudding user response:
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();