javascript - bluebird Promise catch() 未使用 Promise.CancellationError 调用内部函数

标签 javascript node.js promise bluebird

当文件丢失时,我试图取消 promise 。但是,当我这样做时,我在输出中看到:

Unhandled rejection Error: ENOENT, open '/home/one/github/infrastructure_manager_ui/gulp/util/token-file.json'
  at Error (native)

并且 createTokenFile() 也没有按预期运行。不确定我做错了什么:

 function refreshToken() {
        var tokenFile = path.join(__dirname, 'token-file.json');
        return tokenPromise = fs.readFileAsync(tokenFile, {encoding: 'utf-8'})
        .then(JSON.parse)
        .cancellable()
        .catch(Promise.CancellationError, function(err) {
            console.log(err);
            if (err.code !== 'ENOENT') { 
                throw err;
            } else {
                createTokenFile();
                tokenPromise.cancel();
            }
        });
}

最佳答案

.cancellable() 在这里没有执行任何操作。 .cancellable() 将 promise 转变为可以手动取消的 promise 。您没有在此处执行任何操作来取消它,因此它不会被取消。

如果你想捕获文件读取错误,你应该捕获它:

function refreshToken() {
        var tokenFile = path.join(__dirname, 'token-file.json');
        return tokenPromise = fs.readFileAsync(tokenFile, {encoding: 'utf-8'})
        .then(JSON.parse)
        .catch(function(err) {
            console.log(err);
            if (err.code !== 'ENOENT') { 
                throw err;
            } else {
                return createTokenFile();
            }
        });
}

关于javascript - bluebird Promise catch() 未使用 Promise.CancellationError 调用内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28956080/

相关文章:

javascript - 如何使用html按钮执行 Node 功能

mysql - 如何在 javascript (nodejs) 中使用 for 或 foreach 将带有对象值的数组插入到 mysql 中?

node.js - 带有Nodejs的自然语言漫游器(独立Windows应用程序)

javascript - 带有 iron-ajax 响应的 promise

javascript - 尝试找到一种更有效的方法来进行多次替换,而无需在 jQuery 中重复相同的代码

javascript - 用户脚本如何获得有关页面上由 ajax 驱动的更改的通知?

javascript - 在隐藏的 div 中显示和隐藏带有单选按钮的 div

javascript - Chrome 扩展 “Refused to load the script because it violates the following Content Security Policy directive”

javascript - Q.all 链式序列

javascript - 如何更改 promise 内外部变量的值?