gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:36:45 25 4
gpt4 key购买 nike

当文件丢失时,我试图取消 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com