Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

384
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda