javascript - Promise/Block 的 catch 语句都没有执行

标签 javascript promise

我的工作人员中有此代码。

var cBtnStore = {
    a: function(){}
};

现在请注意其中没有 b 键。

然后我的工作线程中有一个函数。它的作用是:

function run() {
    ...
    self.postMessageWithCallback(function() {
        cBtnStore.b(); ////// there is no b key, this should prevent going to the return
    });
    ...
    return promise; // returns a promise
}

var gCB = {};
self.postMessageWithCallback = function(aMsgArr, aCB) {
      var gCBID++;
      aMsgArr.push(gCBID);
      gCB[gCBID] = aCB;
      self.postMessage(aMsgArr);
}

self.onmessage = function(msg) {
    var aCBID = msg.data.pop();
    gCB[aCBID].apply(msg.data);
};

然后我在工作人员中执行此操作:

try {
    run().then(x=>{}, y=>{}).catch(z=>{console.error('promise caught')});
} catch(err) {
     console.log('runComplete threw');
}
console.log('result:', result);

实际发生的情况 - 此日志用于控制台 runComplete() 的返回值,即 “结果:”[Promise 对象]catch.catch 语句都不会执行。

我期望的事情应该发生 - 它应该触发 Promise 或 try-catch block 的 catch 语句。

我的问题 - 有办法实现这个目标吗?

最佳答案

当你写的时候

run().then(x=>{}, y=>{}).catch(z=>{console.error('promise caught')});

你的参数y=>{}实际上意味着“吃掉所有错误”。如果你想看到错误,你应该写

run().then(x=>{}).catch(z=>{console.error('promise caught')});

关于javascript - Promise/Block 的 catch 语句都没有执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35674923/

相关文章:

javascript - 使用 Promises 和 readdir 来显示目录

javascript - iPad 2 上的 Safari 动态加载图像导致内存泄漏

javascript - 为什么 'await' 在函数定义中需要 'async'

javascript - 如何使用 CasperJS 填充未嵌入表单的选择元素?

javascript - React.js - 正确从 API 加载单个帖子数据

javascript - 使用 Spotify API 将我当前在 Spotify 中收听的歌曲添加到网站?

javascript - 如何刷新 promise 链中的数据?

javascript - ES6 Promises 和 PEP3148 Futures 的链式差异

angularjs - 如何在 jasmine 规范中使用 $promise.then 模拟 AngularJS $resource

javascript - JS promise : Allowing Propagation of Errors