我可以假设承诺中的错误会冒出新的Promise并抓住它吗?

toy*_*toy 5 javascript node.js promise bluebird

我有一个函数,如果发现任何东西,它将查找缓存,否则它将继续并获取数据并设置缓存。这是很标准的。我想知道错误是否发生在最内部的函数上,它将使气泡上升到最外部的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?
      });
    });
Run Code Online (Sandbox Code Playgroud)

Bri*_*ber 5

是的,有可能有一个.catch(...)用于深层嵌套的 Promise。窍门:你可以用另一个 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);
  });
Run Code Online (Sandbox Code Playgroud)

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