【问题标题】:bluebird promise catch() is not calling inner function with Promise.CancellationErrorbluebird promise catch() 没有使用 Promise.CancellationError 调用内部函数
【发布时间】:2015-03-10 04:16:30
【问题描述】:

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

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

【问题讨论】:

  • 你为什么要取消它自己的处理程序的承诺?!

标签: javascript node.js promise bluebird


【解决方案1】:

.cancellable() 在这里没有做任何事情。 .cancellable() 将承诺变成可以手动取消的承诺。您没有在此处取消它,所以它没有被取消。

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

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

【讨论】:

  • 不,我也需要取消承诺。我在 else 块内尝试了tokenPromise.cancel();,但没有运气
  • @dman 你不能取消一个已经完成的承诺,如果你已经在那个 else 块中的话。除非承诺已被取消,否则执行甚至不会在您的代码中输入 catch 处理程序。您似乎误解了承诺取消的作用。请参阅this answer 了解详情。
猜你喜欢
  • 2015-09-30
  • 2017-02-10
  • 2017-03-27
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
相关资源
最近更新 更多