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

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

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

假设 .get returns 一个 Promise 你会这样写:

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

无需引入新的 Promise,因为您已经从 _self.get

中获得了一个

是的,对于深层嵌套的 Promise 可以有一个 .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。