gpt4 book ai didi

javascript - 我可以假设 promise 中的错误会冒泡到新的 Promise 并捕获它吗?

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:41 27 4
gpt4 key购买 nike

我有一个函数,如果找到任何内容,它将查找缓存,否则它将继续获取数据并设置缓存。这是非常标准的。我想知道错误是否发生在最内部的函数中,它会一直冒泡到最外层的 Promise 吗?所以,我可以只用一个 catch 而不是一个。

这是我的代码。

我正在使用 Bluebird

 var _self = this;
return new Promise(function(resolve, reject) {
_self.get(url, redisClient).then(function getCacheFunc(cacheResponse) {
if(cacheResponse) {
return resolve(JSON.parse(cacheResponse));
}
webCrawl(url).then(function webCrawl(crawlResults) {
_self.set(url, JSON.stringify(crawlResults), redisClient);
return resolve(crawlResults);
}).catch(function catchFunc(error) {
return reject(error); // can I delete this catch
});
}).catch(function getCacheErrorFunc(cacheError) {
return reject(cacheError); // and let this catch handle everything?
});
});

最佳答案

是的,对于深层嵌套的 Promises 可以有一个 .catch(...)。诀窍:你可以用另一个 Promise 解决一个 Promise。这意味着您可以将代码重构为:

var _self = this;
_self.get(url, redisClient)
.then(function(cacheResponse) {
if(cacheResponse) {
// Resolve the Promise with a value
return JSON.parse(cacheResponse);
}

// Resolve the Promise with a Promise
return webCrawl(url)
.then(function(crawlResults) {
_self.set(url, JSON.stringify(crawlResults), redisClient);

// Resolve the Promise with a value
return crawlResults;
});
})
.catch(function(err) {
console.log("Caught error: " + err);
});

注意:我还删除了最外层的 Promise 声明。这不再是必需的,因为 _self.get(...) 已经返回了一个 Promise。

关于javascript - 我可以假设 promise 中的错误会冒泡到新的 Promise 并捕获它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35345849/

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