How to break promise chain on error

前端 未结 1 1270
不思量自难忘°
不思量自难忘° 2021-01-23 05:19

Consider this snippet

fetch(`http://${api.host}:${api.port}/user`)
  .then(function(data) {
    return data.json();
  }, function(err) {
    throw new Error(`Cou         


        
相关标签:
1条回答
  • 2021-01-23 06:06

    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).

    Your current code works like

    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);
    }
    

    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);
    
    0 讨论(0)
提交回复
热议问题