如何消除这些嵌套的Promises?

Chr*_*oba 2 javascript asynchronous promise ecmascript-6 es6-promise

我已经读过你应该避免在JavaScript中嵌套的promises,因为它们往往是一个反模式,但是我很难弄清楚如何在我的特定用例中避免它们.希望有比我更多经验的人可以看到我哪里出错了?任何建议将不胜感激!

本质上,我正在异步检索一些数据,处理它并捕获可能的错误,然后异步保存一些数据.这是一个非常简单的例子:

class Foo {
  changeName(path, newName) {
      this.getPage(path) // AJAX call, returns a promise with type Page,
                         //  may throw an Error if the page does not exist.
        .then(page=> {
          // Some modifications are made to page, omitted here
          return page
        })
        .catch(e=>{
          if(e instanceof PageDoesNotExistError) {
            return new Page();
          }
        })
        .then(page=> {
          page.name = newName;
          this.savePage(path, page); // ******
          // I want my outer changeName method to return this ^ promise,
          // or at least a promise that will resolve when this promise
          // resolves, with the same value.
        })
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能changeName返回一个将以this.savePage(标记为//******)的值来解析的承诺,以便我可以在其他地方执行以下操作:

myFooInstance.changeName('/path', 'New Name').then(page=> {
  // Do something with the returned saved page
});
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 6

如何让changeName返回一个将使用this.savePage的值解析的promise

savePagethen处理程序返回promise 返回.由此创造的承诺then将奴役自己的承诺.

.then(page=> {
  page.name = newName;
  return this.savePage(path, page);
})
Run Code Online (Sandbox Code Playgroud)

另外,你已经说过你希望调用者能够在返回值上使用promise,changePage但是你没有返回任何东西changePage.您需要return在整个结构前添加,以便返回最终的承诺.

changeName(path, newName) {
  return this.getPage(path) // AJAX call, returns a promise with type Page,
  // ...
Run Code Online (Sandbox Code Playgroud)

(有关完整版本,请参阅下文.)


附注:您在此处等待发生错误:

.catch(e=>{
  if(e instanceof PageDoesNotExistError) {
    return new Page();
  }
})
Run Code Online (Sandbox Code Playgroud)

如果e不是实例PageDoesNotExistError,则将拒绝转换为具有值的分辨率undefined,因为catch在这种情况下处理程序不返回显式值.如果您想要传播错误,则需要使用throw ereturn Promise.reject(e):

.catch(e=>{
  if(e instanceof PageDoesNotExistError) {
    return new Page();
  }
  return Promise.reject(e);
})
Run Code Online (Sandbox Code Playgroud)

所以把所有这三个东西放在一起:

class Foo {
  changeName(path, newName) {
      return this.getPage(path)
        .then(page=> {
          // Some modifications are made to page, omitted here
          return page;
        })
        .catch(e=>{
          if(e instanceof PageDoesNotExistError) {
            return new Page();
          }
          return Promise.reject(e);
        })
        .then(page=> {
          page.name = newName;
          return this.savePage(path, page);
        });
  }
}
Run Code Online (Sandbox Code Playgroud)