server.listen回调没有被错误调用?

时间:2017-02-01 12:44:17

标签: node.js express

  await new Promise((resolve, reject) => {
    console.log('before');
    server.listen(port, err => {
      console.log('after');
      if (err) {
        reject(err);
      }
      resolve();
    });
  });

结果:

before
[ ✘   error  ]  Application encountered an unexpected error, exiting
  2017-02-01T12:38:46.071Z   /home/karlm/dev/node/project/src/index.js:21:19
[ ✘   error  ]  { Error: listen EADDRINUSE :::3030
    at Object.exports._errnoException (util.js:1022:11)
    at exports._exceptionWithHostPort (util.js:1045:20)

正如您所见,before已打印,但不是after?它似乎崩溃而没有调用回调?

2 个答案:

答案 0 :(得分:2)

解决:

  await new Promise((resolve, reject) => {
    server.listen(port, () => {
      resolve();
    }).on('error', (err) => {
      reject(err);
    });
  });

文档并没有暗示我必须使用on

答案 1 :(得分:1)

可以像下面一样使用

server.listen(9000, 'localhost', function() {
    console.log('listening at http://%s:%s', 'localhost', 9000);
}).on('error', (e) => {
    console.error(e.message);
    throw e;
});