How To Use Javascript Async/await On Executing Shell Script
So I have a server listening to RabbitMQ requests: console.log(' [*] Waiting for messages in %s. To exit press CTRL+C', q); channel.consume(q, async function reply
Solution 1:
Since exec
looks like it takes a callback, you can use that to wrap it into a promise. Then you can await that promise instead of awaiting the exec
call directly. So, for your example, something like:
// Await a new promise:awaitnewPromise((resolve, reject) => {
exec('./new_user_run_athena.sh ' + mongodbUserId, function(
error,
stdout,
stderr
) {
console.log('Running Athena...');
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
// Reject if there is an error:returnreject(error);
}
// Otherwise resolve the promise:resolve();
});
});
Solution 2:
See the MDN documentation for await
:
The await operator is used to wait for a Promise. It can only be used inside an async function.
The exec
function does not return a Promise, so you cannot await for it.
You could write a function which wraps exec
in a Promise and returns that Promise though.
Solution 3:
Wrap exec in a promise. Here a typescript example:
import { exec as childProcessExec } from'child_process'const exec = async (command: string): Promise<string> => {
returnnewPromise((resolve, reject) => {
childProcessExec(command, (error, stdout, stderr) => {
if (error !== null) reject(error)
if (stderr !== '') reject(stderr)
elseresolve(stdout)
})
})
}
Usage:
const commandOutput = awaitexec('echo Hey there!')
console.log(commandOutput)
Post a Comment for "How To Use Javascript Async/await On Executing Shell Script"