如何在出错时打破承诺链 [英] How to break promise chain on error

查看:81
本文介绍了如何在出错时打破承诺链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个片段

fetch(`http://${api.host}:${api.port}/user`)
  .then(function(data) {
    return data.json();
  }, function(err) {
    throw new Error(`Couldn\'t fetch user data from server: ${err.message}`);
  }).then(function(eparkUser) {
    for (var key in eparkUser) {
      if (eparkUser.hasOwnProperty(key) && !user.hasOwnProperty(key)) {
        user[key] = eparkUser[key];
      }
    }
    done(null, user);
  }, function(err) {
    throw new Error(`Couldn't parse returned json: ${err.message}`);
  }).catch(function(e) {
    done(e);
  });

不是抛出应该打破链和触发器 .catch ?如何实现这种行为?现在,两个抛出正在执行,我看到消息:

Isn't throw supposed to break the chain and trigger .catch ? How to achieve this behaviour? Becauce now both throw are getting executed and I see message:

错误:无法' t parse返回json:无法从服务器获取用户数据:请求http:// localhost:3010 / user failed 而这不是我想要的。

PS fetch 是npm node-fetch 模块

P.S. fetch is npm node-fetch module

推荐答案

不, throw 不会跳转到 catch 。它拒绝承诺,并且将调用安装在其上的所有错误处理程序。在您的情况下,这是由然后调用安装的错误处理程序。请注意, .catch(handler)只是 .then(null,handler)的糖。

No, throw does not jump to catch. It does reject the promise, and all error handlers installed on it will be invoked. In your case, that's the error handler installed by the then call. Notice that .catch(handler) is just sugar for .then(null, handler).

您当前的代码就像

try {
    try {
        try {
            var data = fetch(`http://${api.host}:${api.port}/user`)
        } catch(err) {
            throw new Error(`Couldn\'t fetch user data from server: ${err.message}`);
        }
        var eparkUser = data.json();
    } catch(err) {
        throw new Error(`Couldn't parse returned json: ${err.message}`);
    }
    for (var key in eparkUser) {
        if (eparkUser.hasOwnProperty(key) && !user.hasOwnProperty(key)) {
            user[key] = eparkUser[key];
        }
    }
    done(null, user);
} catch(e) {
    done(e);
}

要解决您的问题,您需要嵌套处理程序,然后安装仅对该特定承诺的JSON-parse-handler:

To solve your problem, you'll need to nest your handlers, and install the JSON-parse-handler only on that particular promise:

fetch(`http://${api.host}:${api.port}/user`)
    .then(function (data) {
        return data.json()
            .then(function (eparkUser) {
                for (var key in eparkUser) {
                    if (eparkUser.hasOwnProperty(key) && !user.hasOwnProperty(key)) {
                        user[key] = eparkUser[key];
                    }
                }
                return user;
            }, function(err) {
                throw new Error(`Couldn't parse returned json: ${err.message}`);
            });
    }, function(err) {
        throw new Error(`Couldn\'t fetch user data from server: ${err.message}`);
    })
    .then(done.bind(null, null), done);

这篇关于如何在出错时打破承诺链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆