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

370
Views
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 answers
Answer question

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 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!