简体   繁体   English

Node.js Express 响应在 Promise 解决之前结束

[英]Node.js Express response is ended before Promise resolve

Executing following code on Node.js with Express, but it does not return anything.使用 Express 在 Node.js 上执行以下代码,但它不返回任何内容。 It looks like res.send does not work from within promise.then();看起来 res.send 在 promise.then(); 中不起作用; Looks like it already returned back to the caller before promise resolve();看起来它在 promise resolve(); 之前已经返回给调用者了; What I'm doing wrong?我做错了什么? According to examples, it should work.根据示例,它应该可以工作。 Thanks.谢谢。

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

回应

Please add following code to your app: Refer Here请将以下代码添加到您的应用程序:请参阅此处

This app starts a server and listens on port 8080 for connections这个应用程序启动一个服务器并在端口 8080 上侦听连接

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

}) })

You need to listen on a port for the express server to run.您需要监听一个端口才能运行 express 服务器。

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 中的请求超时设置中。

Remove the first删除第一个

res.send('good');

or you could res.write() first then the message should be concatenated when res.send()或者你可以先 res.write()然后在res.send()时连接消息

res.write('good')

res.send() closes the connection between the server and client therefore using res.write() will write the message and when res.send() is sent all the written messages (using res.write()) are sent back to the client called res.send()关闭服务器和客户端之间的连接,因此使用 res.write() 将写入消息,当 res.send() 发送时,所有写入的消息(使用 res.write())将发送回客户叫

IN SHORT简而言之
res.write() can happen several times res.write()可以发生多次
res.send() happens once only per request res.send()每个请求只发生一次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM