使用 AngularJS 应用程序 (1.4.3),我希望 Controller 调用服务上的方法,该方法应返回 bool 值。
在幕后,该服务用于调用 $window.confirm(),然后只返回结果。我正在尝试将实现切换为使用 Angular Material 的 $mdDialog .confirm() API,但这会返回一个 promise 。
我遇到的问题是,如果不更改 Controller 中的代码以期待 promise ,就无法直接从我的服务返回 true 或 false。将此方法提取到服务中的全部目的是使 Controller 可以与调用的实现细节分开,我会考虑使用 promise (即 future bool 值)与直接 bool 值作为实现细节.
下面是一些代码来说明: 在 Controller 中:
function confirmDeleteDevice() {
if (notificationService.confirm('Are you sure you want to delete the device?')) {
deleteDevice();
}
}
“notificationService”中的旧函数:
function confirm(message) {
return $window.confirm(message);
}
notificationService 中的新功能无法按预期使用上述 Controller 代码:
function confirm(message) {
var confirm = $mdDialog.confirm()
.title(message)
.ariaLabel(message)
.ok('Yes')
.cancel('No');
return $mdDialog.show(confirm).then(function() {
return true;
}, function() {
return false;
});
}
在不更改 Controller 代码以依赖使用 promise 的实现细节的情况下,如何从我的服务方法中获取 bool 值?上面的代码将始终执行“deleteDevice()”,因为新的 notificationService.confirm() 将返回 Unresolved promise ,这显然符合 if 子句的真值。
我绝对不是 promise 方面的专家,我知道这并不是它们的预期使用方式,但我真的不想将 Controller 绑定(bind)到使用 promise。鉴于 promise 的“异步”性质,这甚至可能吗?
更新:我在发帖前确实看过,但什么也没找到,但是 this just showed up在“相关问题”提要中,所以我现在看到我的问题是重复的。那里的答案非常有帮助。
最佳答案
您还必须使您的条件异步,通过 promise 链接。
即
notificationService.confirm('...').then(function(confirmation){
if(confirmation) {
deleteDevice();
}
});
你真的不需要 catch 和 return false
除非你需要真正跟踪返回值,因为对话框已经解决/拒绝基于 cancel 或 Ok 的 promise ,即下面的 block 不会需要。
.then(function() {
return true;
}, function() {
return false;
});
所以
function confirm(message) {
var confirm = $mdDialog.confirm()
.title(message)
.ariaLabel(message)
.ok('Yes')
.cancel('No');
return $mdDialog.show(confirm);
}
只是:
notificationService.confirm('...').then(deleteDevice);
关于javascript - 如何根据 promise 的结果返回 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32405179/