[英]Q promise chaining, error handler not called
Consider this code 考虑这段代码
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));
};
And call: 并致电:
tryWithoutReindexing(indexName, newProperties)
.then(function success(value){
console.log('migration successful');
}, function error(){
console.log('migration unsuccessful');
});
Method elastic.putSettings
throws error, but for some reason, console
logs 'migration is successful'
. 方法elastic.putSettings
引发错误,但由于某些原因, console
日志'migration is successful'
。 I would expect error handler to be called. 我希望错误处理程序被调用。
If I change method to this: 如果我将方法更改为此:
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));
};
, and put breakpoint in line console.log(error);
,并将断点放在console.log(error);
行中console.log(error);
, the error handler is called, so it seems that putSettings method works correctly. ,错误处理程序就会被调用,因此putSettings方法似乎可以正常工作。
Does anyone can explain me why first example doesn't handle error raised in promise chain? 有谁能解释我为什么第一个示例不能处理Promise链中引发的错误?
I assume that elastic.putSettings()
et al return a promise. 我假设elastic.putSettings()
等返回了诺言。 You can't use a promise as an argument for .then
; 您不能将诺言用作.then
的参数; that method expects function arguments. 该方法需要函数参数。 In turn though, these functions can return a promise. 但是,这些函数可以依次返回一个承诺。
So, you need to wrap your promise-returning functions with an anonymous function, and use that function as the argument for the .then
's. 因此,您需要使用匿名函数包装返回承诺的函数,并将该函数用作.then
的参数。 Like so: 像这样:
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);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.