I have a PHP script which uses the exec function to execute a Node script and return some data back to the same PHP script.
My issue is that I need to return the data back to PHP without having to wait for the cleanup code in finally to finish.
I have written some example code below to show you how the code flows and illustrate my issue. The code example does not use any node modules but feel free to use them if they will help.
example.php
$data = 'hello world';
$exec = 'node example.js ' . $data;
$escaped_command = escapeshellcmd($exec);
$data = exec($escaped_command);
// waits 10 seconds then displays returned data
// I need the code to return before finally executes
var_dump($data); // string(31) "Final data is final hello world"
example.js
let data = process.argv[2];
// let data = "hello world";
async function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const doSomething = data => new Promise((resolve, reject) => {
if (data) {
resolve("new hello world");
} else {
reject();
}
});
const doSomethingElse = newData => new Promise((resolve, reject) => {
if (newData) {
resolve("final hello world");
} else {
reject();
}
});
(async() => {
try {
let newData = await doSomething(data);
let finalData = await doSomethingElse(newData);
// return this to server/php right now.
// Do not wait until finally script finishes
console.log("Final data is " + finalData);
} catch (err) {
// if error return this to server/php right now.
// Do not wait until finally script finishes
console.log(err);
} finally {
// does cleanup/closes node app
await timeout(10000);
}
})();