考虑这段代码
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 :(得分:2)
我认为elastic.putSettings()
等人会回复承诺。您不能将承诺用作.then
的参数;该方法需要 function 参数。反过来,这些函数可以返回一个承诺。
因此,您需要使用匿名函数包装promise-returns函数,并将该函数用作.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);
});
};