0

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);
}())
dun
  • 353
  • 1
  • 2
  • 18

1 Answers1

2

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.

TheBlueOne
  • 486
  • 5
  • 13
  • Ok I didn't read it thoroughly, the delay is just to simulate the asynchronous callback. I still have issues to wrap my head around this. But I don't think this would help me in that particular case because all it does is making the value only available in another callback function. – dun Dec 13 '21 at 13:33
  • I think I got it now, I'm going to update my post. Thanks for the help. – dun Dec 13 '21 at 13:47