【发布时间】:2017-08-02 16:57:55
【问题描述】:
我读到您应该避免 JavaScript 中的嵌套承诺,因为它们往往是一种反模式,但我无法弄清楚如何在我的特定用例中避免它们。希望比我更有经验的人能看到我哪里出错了?任何建议将不胜感激!
基本上,我异步检索一些数据,处理它并捕获可能的错误,然后异步保存一些数据。这是一个非常简化的示例:
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.
})
}
}
我怎样才能让changeName 返回一个将解析为this.savePage 值的承诺(标有//****** 的行),以便我可以在其他地方做这样的事情:
myFooInstance.changeName('/path', 'New Name').then(page=> {
// Do something with the returned saved page
});
【问题讨论】:
-
呃,只是
return吗?请注意,还没有任何嵌套。
标签: javascript asynchronous ecmascript-6 promise es6-promise