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

309
Vistas
JavaScript: Defining a global variable inside a setTimeout

I am trying to define a global variable c inside a setTimeout function where promise is involved.

I tried the following code based on the answer here. But this did not work!

This code involves asynchronous and I do understand that the function test is non-blocking for console.log(c) and that is why I received an "undefined" outcome. How may I solve this issue?

let k = new Promise((resolve, reject) => {
  if (2 < 4) {
    resolve('you are okay');
  } else {
    reject('You are not okay');
  }
});

var c;

function test() {
  setTimeout(() => {
    c = k.then(x => console.log(x,"x in then"));
     console.log(c,"in setTimeout")
  }, 2000);
}

test();

console.log(c,"outside");

about 4 years ago · Juan Pablo Isaza
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