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);
}())