如何在退出时执行异步操作 [英] How to perform an async operation on exit

查看:78
本文介绍了如何在退出时执行异步操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试终止进程之前执行异步操作.

I've been trying to perform an asynchronous operation before my process is terminated.

说终止"是指终止的所有可能性:

Saying 'terminated' I mean every possibility of termination:

  • ctrl + c
  • 未捕获的异常
  • 崩溃
  • 代码结尾
  • 任何事情..

据我所知, exit 事件仅用于同步操作.

To my knowledge the exit event does that but for synchronous operations.

在阅读Nodejs文档时,我发现了 beforeExit 事件用于异步操作BUT:

Reading the Nodejs docs i found the beforeExit event is for the async operations BUT :

对于导致显式终止的条件(例如调用 process.exit()或未捕获的异常),不会发出'beforeExit'事件.

The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions.

除非打算安排其他工作,否则不应将"beforeExit"用作"exit"事件的替代方法.

有什么建议吗?

推荐答案

您可以在退出之前捕获信号并执行异步任务.这样的事情会在退出之前调用terminator()函数(甚至代码中的javascript错误):

You can trap the signals and perform your async task before exiting. Something like this will call terminator() function before exiting (even javascript error in the code):

process.on('exit', function () {
    // Do some cleanup such as close db
    if (db) {
        db.close();
    }
});

// catching signals and do something before exit
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
    'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function (sig) {
    process.on(sig, function () {
        terminator(sig);
        console.log('signal: ' + sig);
    });
});

function terminator(sig) {
    if (typeof sig === "string") {
        // call your async task here and then call process.exit() after async task is done
        myAsyncTaskBeforeExit(function() {
            console.log('Received %s - terminating server app ...', sig);
            process.exit(1);
        });
    }
    console.log('Node server stopped.');
}

添加评论中要求的详细信息:

Add detail requested in comment:

  • 节点的文档中解释的信号,此链接引用标准的
  • Signals explained from node's documentation, this link refers to standard POSIX signal names
  • The signals should be string. However, I've seen others have done the check so there might be some other unexpected signals that I don't know about. Just want to make sure before calling process.exit(). I figure it doesn't take much time to do the check anyway.
  • for db.close(), I guess it depends on the driver you are using. Whether it's sync of async. Even if it's async, and you don't need to do anything after db closed, then it should be fine because async db.close() just emits close event and the event loop would continue to process it whether your server exited or not.

这篇关于如何在退出时执行异步操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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