Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
stop and execute a promise javacript

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!