Node.js Express响应在Promiseparsing之前结束

使用Express在Node.js上执行以下代码,但不返回任何内容。 看起来res.send在promise.then()中不工作。 看起来它已经返回给调用方之前承诺解决(); 我做错了什么? 根据例子,它应该工作。 谢谢。

const express = require('express'); const app = express(); app.get('/test', (req, res, next) => { res.send("Good"); // Works Just Fine , but I dont need to return here getMessage().then(function(data){ console.log("I'm here"); // Message works res.send("Good"); // Does not Work }).catch(function(error){ res.send("Error"); }); }); function getMessage(){ return new Promise(function(resolve, reject){ setTimeout(function() { resolve(); }, 3000); }); } app.listen(PORT, () => { console.log("run"); }); 

响应

请将以下代码添加到您的应用中: 请参阅此处

这个应用程序启动一个服务器,并监听端口8080连接

 app.listen(8080, function () { console.log('Example app listening on port 8080!') 

})

您需要侦听端口才能运行快速服务器。

 const express = require('express'); const app = express(); const port = process.env.PORT || 3000; app.get('/test', (req, res, next) => { getMessage().then(function(data){ res.send("Good"); }).catch(function(error){ res.send("Error"); }); }); function getMessage() { return new Promise((resolve, reject) => { setTimeout(function() { resolve(); }, 3000); }); } app.listen(port, () => console.log(`App listening at http://localhost:${port}`)); 

问题是Postman中的请求超时设置,我用于testing。