I want to assign the value inside a callback function to a variable outside of it. Here is an example with child_process.
let variable;
require('child_process').spawn('python', ['./hello.py']).stdout.on('data', data => {
variable = data.toString();
console.log(variable);
});
console.log(variable);
print('Hello World')
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?
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);
}())
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.