我还没有完全理解承诺,如果这是一个简单的误解,我深表歉意。
我有一个删除页面上项目的功能,但我有一个特定的行为,具体取决于页面的状态。伪代码方面是这样的:
Does the page have changes?
If yes - prompt to save changes first
If yes - save changes
If no - exit function
If no - continue
Prompt to confirm delete
If yes - delete item and reload data
If no - exit function
希望这是有道理的。本质上,如果有更改,则必须首先保存数据。然后,如果数据已保存,或者如果开始时没有更改,则提示用户确认删除。问题是我正在使用 durandal 和微风,我似乎无法将它们正确返回的承诺链接在一起。
我的功能目前看起来像这样,我知道这是错误的,但我正在努力找出在哪里修复它。
if (this.hasChanges()) {
app.showMessage('Changes must be saved before removing external accounts. Would you like to save your changes now?', 'Unsaved Changes...', ['Yes', 'No'])
.then(function (selectedOption) {
if (selectedOption === 'Yes') {
return this.save();
} else {
Q.resolve()
}
});
}
app.showMessage('Are you sure you want to delete this item?', 'Delete?', ['Yes', 'No'])
.then(function (selectedOption) {
if (selectedOption === 'Yes') {
item.entityAspect.setDeleted();
datacontext.saveChanges()
.then(function () {
logger.logNotificationInfo('Item deleted.', '', router.activeInstruction().config.moduleId);
Q.resolve(this.refresh(true));
}.bind(this));
}
}.bind(this));
来自 durandal 的 app.showMessage 调用返回一个承诺,然后 this.save 返回一个承诺,最后 this.refresh 也返回一个承诺。
所以我想我需要检查 hasChanges,然后在必要时调用 save 并解决它。然后在该条件部分完成解析后,调用第二个提示,然后解析其中的所有承诺。
对不起,我认为这不是很清楚,但我认为这也是因为我没有完全遵循这里的链条。
非常感谢任何帮助!谢谢。