【问题标题】:returning data to a middleware from a promise从 promise 返回数据到中间件
【发布时间】:2017-03-03 00:17:06
【问题描述】:

我是 nodejs 的新手,这可能看起来很简单,但我无法从返回承诺的函数中检索数据。来自中间件的响应被发送回前端。这是我的代码

// middleware
app.get('/player', function(req, res) {
             //data i want to return
    res.send(getPlayerStats.getPlayerId(req.query.name)));
});

//getPlayerStats.js
var getPlayerId = function(name) {
    return start(name)
       .then(getPlayerInGame)
       .then(getPlayerStats)
       .then(getPlayers); 
     //.then(sendToSingular)
}

//getplayers function
var getPlayers = function(data) {
   return data; 
}

我以错误的方式发回数据?我在前端看到的响应是一个以原型为唯一属性的对象。我可以打印出 getPlayers() 中的数据,我发现它工作正常。

【问题讨论】:

  • 您不能在稍后返回结果的异步方法上调用res.send,您必须在异步方法的回调内部发送

标签: javascript node.js express promise


【解决方案1】:

那是因为您将 Promise 本身传递给 res.send

res.send(/* You are passing a promise here */);

你应该做的是等待承诺解决数据,然后发送该数据:

getPlayerStats.getPlayerId(req.query.name).then(function(data) {
  res.send(data);
});

【讨论】:

  • @inhaler 没问题的朋友,很高兴为您提供帮助。以下是一些有用的资源(this onethis one),可用于了解有关 Promise 的更多信息
【解决方案2】:

我总是建议使用catch() 来完成您的承诺链,以确保错误得到处理:

getPlayerStats.getPlayerId(req.query.name)
  .then(function(data) {
    res.send(data);
  })
  .catch(function(error){
    res.status(500).send('Some error text');
  });

【讨论】:

    【解决方案3】:

    当您编写中间件时,听起来您希望玩家 ID 可用于其他操作,因此除了此处的其他 cmets:

    app.get('/player/*', function(req, res, next) {
                 //data i want to return
        getPlayerStats.getPlayerId(req.query.name))).then(function(id){
          res.locals.playerId = id;
          next();
        });
    });
    
    
    app.get('/player/action', function(req, res){
        res.send(res.locals.playerId); //or use it for further processing
    });
    

    【讨论】:

    • 当我开始处理这个项目的其他部分时,这肯定会非常有用。非常感谢!
    猜你喜欢
    • 2017-11-16
    • 2018-04-07
    • 2020-05-18
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多