【问题标题】:When and how to return an http response only when a promise is complete?仅当 Promise 完成时,何时以及如何返回 http 响应?
【发布时间】: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


    【解决方案1】:

    您需要删除 res.send('test');。你写给她的方式 send 将在 promise 执行更改之前完成请求。

    【讨论】:

    • 取出 res.send('test') 它只是坐在终端等待响应,但从未收到。调用响应之前的 console.log(result_message) 行并在控制台中显示返回的数据,所以我确定它正在响应数据,只是由于某种原因没有将响应冒泡回客户端.
    • 解决方案相当简单,感谢@NotMyself 的在线黑客会议。我们将抽象提升到了一个更好的层次,其中 api.stuff_by_id 只是返回了一个从 luceneDb.search 函数返回的 Promise 的 Promise。一旦它冒泡到上层,然后在 .then 调用 promise 以完成并将响应(res.send)发送回客户端。我将在上面的问题中添加代码并将您的答案标记为已选中。 :)
    【解决方案2】:

    res.send('test') 的问题是响应将在 Lucene 调用结束之前发送给客户端,因此,当您将获得第二个 res 时,客户端已经消失了。发送。

    关于 promise,我使用 .them(function(result) {}, function(err) {});不是.then().fail(),你用什么模块?

    对于 LuceneDB,您还使用什么模块?我只是好奇。

    【讨论】:

      猜你喜欢
      • 2013-10-12
      • 1970-01-01
      • 2014-12-25
      • 2021-09-30
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      相关资源
      最近更新 更多