2014-03-12 58 views
1

我有以下代碼何時以及如何僅在承諾完成時才返回http響應?

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

我意識到這樣做對這一呼籲的捲曲請求時,將顯示唯一的反應是最後的反應,因爲其他人都還在爲分裂處理第二。然而,我實際上需要res.send(result)或res.send(err)調用給出響應而不是res.send('test')。什麼是使服務器等待用正確的響應之一進行響應的方法?有沒有辦法等待或以某種方式來做這件事?

謝謝!

解決方案(@NotMyself下面回答,而是幫助我去下面的代碼脫機)。解決方案相當簡單,儘管起初並不明顯。

我們將抽象提升到了一個更好的級別,其中api.stuff_by_id剛剛返回了luceneDb.search函數返回的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; 
     }) 
}; 

提供的顧慮少泄漏了。

回答

2

您需要刪除res.send( '測試');.你寫它的方式將在承諾執行更改之前完成請求。

+0

掏出res.send(「試驗」),它只是在終端位於等待響應但一個是從未接受。 console.log(result_message)行恰好在調用響應之前顯示在控制檯中返回的數據,所以我確信它正在響應數據,它只是沒有得到響應,由於某種原因回覆給客戶端。 – Adron

+0

解決方案相當簡單,感謝@NotMyself在線黑客會話。 我們拉到抽象出更好的水平,其中api.stuff_by_id剛剛返回從luceneDb.search函數返回的承諾的承諾。一旦達到最高水平,那麼就會被使用,然後根據承諾的完成調用完成並將響應(res.send)發送回客戶端。 我打算將代碼添加到上述問題中,並將您的答案標記爲已選中。 :) – Adron

1

與res.send(「測試」)的問題是,響應將發送到客戶端的Lucene的通話結束前,正因爲如此,客戶端已經走了的時候,你就會有第二個水庫。發送。

關於諾言,我用.them(函數(結果){}功能(ERR){});不.then()。失敗(),你使用什麼模塊?

而對於LuceneDB你用什麼模塊呢?我只是好奇。

相關問題