【发布时间】:2014-03-12 20:24:06
【问题描述】:
我有以下代码
api.stuff_by_id = function (req, res) {
var collection = collectionName;
var search = getLuceneSearchString(req.body);
luceneDb.search(collection, search)
.then(function (result) {
var result_message = result.body;
console.log(result_message);
res.send(result); // this is the response I'd actually like to see returned.
})
.fail(function (err) {
console.log(err);
res.send(err); // or this one if there is an error.
})
res.send('test'); // however this is the only one that gets returned.
};
我意识到,在针对此调用执行 curl 请求时唯一显示的响应是最后一个响应,因为其他响应仍在处理一瞬间。但是我实际上需要让 res.send(result) 或 res.send(err) 调用给出响应而不是 res.send('test')。有什么方法可以让服务器等待以正确响应之一响应?有没有办法以某种方式等待或其他方法来做到这一点?
谢谢!
解决方案 (@NotMyself 在下面回答,但帮助我离线获取以下代码)。解决方案相当简单,尽管一开始并不完全明显。
我们将抽象提升到了一个更好的层次,其中 api.stuff_by_id 只是返回了一个从 luceneDb.search 函数返回的 Promise 的 Promise。一旦它冒泡到上层,然后在 .then 调用 promise 以完成并将响应(res.send)发送回客户端。以下是该方法之后的样子。
帖子的功能设置如下:
app.post('/identity/by',
passport.authenticate('bearer', { session: false}),
function (req, res) {
luceneDb.search(req.body)
.then(function (result) {
res.send(result);
})
.fail(function (err) {
res.statusCode = 400;
res.send(err);
});
});
luceneDb.search 函数如下所示:
luceneDb.search = function (body) {
var collection = data_tier.collection_idents;
var search = getLuceneSearch(body);
if (search === '') {
throw new Error
'Invalid search string.';
}
return orchestrator.search(collection, search)
.then(function (result) {
var result_message = result.body;
console.log(result_message);
return result.body;
})
};
也减少了问题的泄漏。
【问题讨论】:
标签: javascript api http response promise