退出时的nodejs(SIGTERM / SIGINT),获得一个工作的承诺(使用sails)

时间:2018-03-27 22:09:05

标签: node.js promise sigint

我正在尝试添加一个选项来优雅地结束sails服务器(在docker中运行)。这需要我写一些东西到数据库,以便服务器的其他副本知道这个特定的服务器已“死”。

在nodejs进程之后,我可以用:

拦截stop命令
const util = require("util");
const setTimeoutPromise = util.promisify(setTimeout);
process.on('SIGTERM', function() {
  endMe('exiting - sigterm');
});


process.on('SIGINT', function() {
  endMe('exiting - sigint');
});

function endMe(msg) {
  console.log('trying to end it');
  setTimeoutPromise(1).then(function (res) {
    console.log('killed it');
    sails.lower(function(err) {
      console.log(msg);
      process.exit(err ? 1 : 0)
    });
  }).catch(function (err) {
    console.log("error occured");
    console.log(err);
    sails.lower(function(err) {
      console.log(msg);
      process.exit(err ? 1 : 0)
    });
  })
}

请忽略setTimeoutPromise的重要性 - 它就是mvce的存在。 Ultimatelly我希望在退出时将一些数据写入数据库。 (服务器应该在集群中运行,因此通过写入数据库,我通知服务器已正常结束)。

我在控制台/终端中看到的是:

trying to end it
Process finished with exit code 0

不应该是这种情况。 - 这意味着承诺永远不会被执行。

0 个答案:

没有答案