我正在尝试使用带有 promise 的express,但无法使其工作。
当我取消注释 (1)
时,我可以将响应设置为 200,但无论我尝试在 promise (2,3,4)
中设置响应,它总是返回 401
我可以在 then
中 console.log
data
所以 promise 肯定会解决,但我相信 401
是发送是因为函数不会等待 Promise 得到解决,对吗?
我做错了什么以及如何设置 promise 的响应?
提前致谢!
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);
});
});
最佳答案
您需要在tree.getData
之前添加一个return来返回promise及其结果。 A+ Promise 具有 catch()
而不是 fail()
此外,在 Express 中设置状态代码时,您需要使用 res.status().send()
而不是 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);
});
});
关于javascript - 使用带有 Promise 的 Express.js 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043769/