inhaler inhaler - 1 month ago 10
Javascript Question

returning data to a middleware from a promise

i am new to nodejs, this might seem pretty trivial but i am having trouble retrieving data from a function that returns a promise. The response from the middleware is sent back to the front end. Here is my code

// 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;
}


I'm i sending the data back the wrong way? The response i see at the front end is an object with prototype as the only property. I can print out the data in getPlayers() and i see it is working fine.

Answer

That's because you're passing the promise itself into res.send.

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

What you should do is wait for the promise to resolve with the data and and then send that data:

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