Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda