Reputation: 6720
I am trying to use express with promises but I can't make it work.
when I uncomment (1)
I can set response as 200, but whatever I try to set as response in promise (2,3,4)
It always returns 401
I can console.log
data
in then
so promise is surely resolving but I believe that 401
is send because function doesn't wait for promise to be resolved is that right?
What I'm doing wrong and how I can set response from promise?
Thanks in advance!
app.get('/get_data', function (req, res) {
//res.json(200, {}); return; --> (1) gives expected 200
tree.getData(req.param('ids'))
.then(function (data) {
// console.log('data'); --> (2) logs requested array of data
//return res.json(200,{}); --> (3) gives 401
return res.send(data); // --> (4) gives 401
}).fail(function (err) {
// never goes here
console.log(err);
return res.json(550, err);
});
});
Upvotes: 2
Views: 3652
Reputation: 19418
You need to add a return before tree.getData
to return the promise and its result. An A+ Promise has catch()
not fail()
Also when setting a status code in Express you need to use res.status().send()
not res.send(status, data)
Express res.send()
Docs
app.get('/get_data', function (req, res) {
return tree.getData(req.param('ids'))
.then(function (data) {
return res.status(200).send(data)
}).catch(function (err) {
// never goes here
console.log(err);
return res.status(550).json(err);
});
});
Upvotes: 5