ES6承诺在捕获之前返回

时间:2017-03-26 14:30:35

标签: javascript ecmascript-6 promise es6-promise

如何实现saveThings()的调用者获得精确的错误描述(A或B)。目前,我拒绝接受类型A get在catch()子句中被捕获,因此调用者总是以消息B结束...

saveThings() {
    return api.post(endpoint, data)
    .then( response => {
        if ( !response )
            reject({message: 'error of type A - faulty response'});

        resolve('all went well');
    })
    .catch( err => {
        throw new Error('error of type B - call failed');
    });
}

2 个答案:

答案 0 :(得分:3)

您需要use .then(…, …) instead of .then(…).catch(…)

return api.post(endpoint, data).then(response => {
    if (!response)
        throw {message: 'error of type A - faulty response'};
    return 'all went well';
}, err => {
    throw new Error('error of type B - call failed');
});

答案 1 :(得分:2)

嗯,这取决于什么时候,因此你会抓到什么

saveThings() {
    return api.post(endpoint, data)
        .catch(err => {
            throw new Error('error of type B - call failed');
        })
        .then( response => {
            if ( !response )
                throw new Error('error of type A - faulty response');

            return 'all went well';
        });
}

saveThings() {
    return api.post(endpoint, data)
        .then( response => {
            if ( !response )
                throw new Error('error of type A - faulty response');

            return 'all went well';
        }, err => {
            throw new Error('error of type B - call failed');
        });
}

几乎相同。只有第一个创建了一个中间的Promise,在catch后,第二个没有。