javascript - Q promise 链接,未调用错误处理程序

标签 javascript promise 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抛出错误,但由于某种原因,控制台记录“迁移成功”。我希望调用错误处理程序。

如果我将方法更改为:

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/

相关文章:

javascript - 从数组中的链接下载文件

javascript - 我如何处理错误然后立即脱离 promise 链?

javascript - AngularJS 等待单个异步调用

javascript - 无需单击或按任何键(复选框)即可添加事件类

javascript - 三.js从ObjLoader中操作一个对象

javascript - 使用带有 Fetch API 响应的 promise 仍然会使我的数据返回为未定义

javascript - 函数返回 Promise,检查错误

javascript - Mongoose promise 和 Q promise

javascript - Node.js 服务器的哪个 Websocket 库最适合 iOS 客户端?

javascript - 无法让 Bootstrap 插件工作