javascript - ES6 Promises 在 catch 之前返回

标签 javascript ecmascript-6 promise es6-promise

我怎样才能实现 saveThings() 的调用者获得精确的错误描述(A 或 B)。目前,我对 A 类型的拒绝被 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');
    });
}

最佳答案

您会想要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');
});

关于javascript - ES6 Promises 在 catch 之前返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43030023/

相关文章:

javascript - REACT : On render, 给每个div一个唯一的className

javascript - 光学变焦禁用

JavaScript ES6 模块 + traceur

javascript - 将 dojo/Deferred 与异步函数和查询结合使用

javascript - Await 内的代码未在 Expo App 中运行

javascript - 使用 JavaScript 或 jQuery 更改 CSS 规则

javascript - 多级水平菜单 CSS

javascript - JavaScript 是否允许用 "method references"替换 lambda ?如果没有,为什么不呢?

typescript - ES6 与 TypeScript 中的泛型类型混合

javascript - 如何让 promise 同步执行?