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

371
Vistas
NodeJS: Assign the value inside a callback function to a variable outside of it

I want to assign the value inside a callback function to a variable outside of it. Here is an example with child_process.

callback.js

let variable;
require('child_process').spawn('python', ['./hello.py']).stdout.on('data', data => {
    variable = data.toString();
    console.log(variable);
});

console.log(variable);

hello.py

print('Hello World')

output:

undefined
Hello World

I know that the console.log at the bottom is being executed before the callback function and therefore the variable is still undefined. But how could I wait for the callback function to finish first?

Solution:

Promises seem to be the optimal answer and the code needs to be asynchronous.

async function test() {
    const promise = new Promise((resolve, reject) => {
        require('child_process').spawn('python', ['./test.py']).stdout.on('data', data => {
            resolve(data.toString());
        });
    });
    return promise;
}

(async function () {
    let variable;
    await test().then(res => {
        variable = res;
    });

    console.log(variable);
}())
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use a promise to wait for the callback like in this example:

let data;
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    data="abc";
    resolve('foo');
  }, 300);
});

myPromise.then((res)=>{console.log(data+res)})

this will print out "abcfoo"

Often the best way to wait for something asynchronous is to have asynchronous code yourself.

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