考虑这段代码
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
抛出错误,但由于某种原因,控制台
记录“迁移成功”
。我希望调用错误处理程序。
如果我将方法更改为:
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 方法工作正常。
有人可以解释为什么第一个示例不处理 promise 链中引发的错误吗?
最佳答案
我假设elastic.putSettings()
等人返回一个 promise 。您不能使用 Promise 作为 .then
的参数;该方法需要函数参数。但反过来,这些函数可以返回一个 promise 。
因此,您需要使用匿名函数包装您的 promise 返回函数,并使用该函数作为 .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);
});
};
关于javascript - Q promise 链接,未调用错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37551138/