2016-05-31 56 views
0

考慮以下代碼Q承諾鏈接,錯誤處理程序不叫

var tryWithoutReindexing = function(indexName, properties) { 
     var settings = properties["settings"]; 
     var mappings = properties["mappings"]; 
     return elastic.closeIndex(indexName) 
      .then(elastic.putSettings(indexName, settings)) 
      .then(elastic.putMapping(indexName, mappings)) 
      .then(elastic.openIndex(indexName)); 
}; 

而且撥打:

tryWithoutReindexing(indexName, newProperties) 
.then(function success(value){ 
     console.log('migration successful'); 
    }, function error(){ 
     console.log('migration unsuccessful'); 
    }); 

方法elastic.putSettings拋出錯誤,但由於某些原因,console日誌'migration is successful'。我希望錯誤處理程序被調用。

如果我改變的方法是:

var tryWithoutReindexing = function(indexName, properties) { 
     var settings = properties["settings"]; 
     var mappings = properties["mappings"]; 
     return elastic.closeIndex(indexName) 
      .then(elastic.putSettings(indexName, settings)) 
       .then(function success() { 
       console.log('err'); 
      }, function(error) { 
       console.log(error); 
      }) 
      .then(elastic.putMapping(indexName, mappings)) 
      .then(elastic.openIndex(indexName)); 
}; 

,並把符合console.log(error);斷點,錯誤處理程序被調用,因此它似乎putSettings法正常工作。

有沒有人可以解釋我爲什麼第一個例子不處理承諾鏈中出現的錯誤?

+0

它似乎並沒有顯示您的實際代碼。你的替代版本的方法有分配'settings'和'mappings'的行,而你的第一個版本沒有這個,但仍然使用這些變量。請將您的代碼削減爲實際產生問題的內容,但是您可以在此修改此內容。我們需要看到實際的代碼,因爲魔鬼在細節中。 – JLRishe

+0

@JLRishe更新,這是唯一的區別,我省略了簡潔 – Raston

回答

2

我假設elastic.putSettings()等人返回一個承諾。你不能使用承諾作爲.then的參數;該方法預計函數參數。反過來,這些功能可以返回一個承諾。

所以,你需要用匿名函數包裝你的承諾返回函數,並使用該函數作爲.then的參數。像這樣:

var tryWithoutReindexing = function(indexName, properties) { 
    var settings = properties["settings"]; 
    var mappings = properties["mappings"]; 

    return elastic.closeIndex(indexName) 
       .then(function() { 
        return elastic.putSettings(indexName, settings); 
       }) 
       .then(function() { 
        return elastic.putMapping(indexName, mappings); 
       }) 
       .then(function() { 
        return elastic.openIndex(indexName); 
       }); 
}; 
+0

好吧,答案是正確的,但我需要一些澄清。 elastic.putSettings(indexName,settings)是一個返回承諾的函數包裝器: putSettings:function(indexName,settings){ return client.indices.putSettings({index}:indexName, body:settings }); }, 那麼爲什麼這不起作用呢?這是一個函數的參數,而不是一個承諾(我猜) – Raston

+0

我明白我的想法。我所做的是用參數調用函數,這導致了承諾。有沒有辦法通過參數傳遞函數引用來綁定?脂肪箭頭和函數包裝是選項,但我正在尋找一個班輪更乾淨的代碼 – Raston

+1

@Raston試試這個:'.then(elastic.putSettings.bind(elastic,indexName,settings))'(它確實使代碼更多簡潔但不一定更清潔IMO) – robertklep