How to use javascript async/await on executing shell script

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-11 12:11:23

问题


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(msg) {
            const mongodbUserId = msg.content.toString();
            console.log(' [x] Received %s', mongodbUserId);

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

            console.log(
                ' Finished running Athena for mongodbUserId=%s',
                mongodbUserId
            );

            channel.sendToQueue(
                msg.properties.replyTo,
                new Buffer(mongodbUserId),
                { correlationId: msg.properties.correlationId }
            );

            channel.ack(msg);
        });

The problem is that the await call on executing the shell script new_user_run_athena.sh happens after I print out Finished running Athena for mongodbUserId. You can see it happening in the console log:

 [*] Waiting for messages in run_athena_for_new_user_queue. To exit press CTRL+C
 [x] Received 5aa96f36ed4f68154f3f2143
 Finished running Athena for mongodbUserId=5aa96f36ed4f68154f3f2143
Running Athena...
stdout: 
stderr:

Is it even possible to use async await syntax on executing a shell script?


回答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:
await new Promise((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:
            return reject(error);
        }

        // Otherwise resolve the promise:
        resolve();
    });
});



回答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.



来源:https://stackoverflow.com/questions/50219748/how-to-use-javascript-async-await-on-executing-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!