如何在执行shell脚本时使用javascript async/await [英] How to use javascript async/await on executing shell script

查看:101
本文介绍了如何在执行shell脚本时使用javascript async/await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一台服务器正在监听RabbitMQ请求:

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

问题在于执行shell脚本 new_user_run_athena.sh 的等待调用发生在我打印出 mongodbUserId 的已完成运行的雅典娜之后.您可以在控制台日志中看到它的发生:

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:

在执行Shell脚本时是否甚至可以使用异步等待语法?

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

推荐答案

由于 exec 看起来需要回调,因此您可以使用该回调将其包装为promise.然后,您可以等待该承诺,而不必直接等待 exec 调用.因此,以您的示例为例,

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

这篇关于如何在执行shell脚本时使用javascript async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆