我是否可以假设承诺中的错误会冒泡到新的承诺并抓住它

Can I assume that error in a promise will bubble to new Promise and catch that?

本文关键字:承诺 错误 是否 假设 误会      更新时间:2023-09-26

>我有一个函数,如果它找到任何东西,它将查找缓存,否则它将继续获取数据并设置缓存。这是非常标准的。我想知道如果错误发生在最内部的功能,它会保持气泡到最外部的承诺吗?所以,我可以只有一个catch而不是一个。

这是我的代码。

我正在使用蓝鸟

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

是的,对于深度嵌套的承诺,可以有一个.catch(...)。 诀窍:你可以用另一个承诺来解决一个承诺。 这意味着您可以重构代码以:

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

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

假设.get返回一个承诺,你会这样写:

 var _self = this;
 return _self.get(url, redisClient).then(function(cacheResponse) {
   if (cacheResponse) {
     return JSON.parse(cacheResponse);
   } else {
     return webCrawl(url).then(function(crawlResults) {
       _self.set(url, JSON.stringify(crawlResults), redisClient);
       return crawlResults;
     })
   }
 });

没有必要引入新的承诺,因为你已经从你的_self.get那里得到了一个承诺