How do you return a boolean based on the result of a promise?

Working with an AngularJS application (1.4.3), I want the controller to make a method call in a service that should return a boolean.

Under the hood, the service used to call $ window.confirm (), and then simply returns the result. I am trying to switch the implementation to using the Angular Material $ mdDialog .confirm () API, but this returns a promise.

The problem I am facing is that there is no way to return true or false directly from my service without changing my controller code to wait for a promise. The whole purpose of extracting this method into the service was that the controller could be separated from the details of the call implementation, and I would consider using the promise (i.e. the future logical) as compared to the direct logical, to be a detail of the implementation.

Here is some code to illustrate: In the controller:

function confirmDeleteDevice() {
    if (notificationService.confirm('Are you sure you want to delete the device?')) {
        deleteDevice();
    }
}

Old function in 'notificationService':

function confirm(message) {
    return $window.confirm(message);
}

A new feature in the notification service that will not work properly with the controller code above:

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;
    });
}

, , ? "deleteDevice()", Service.confirm() , , -, if.

promises, , , , . "" promises?

: , , " ", , . .

+4
1

, .

notificationService.confirm('...').then(function(confirmation){
     if(confirmation) {
         deleteDevice();
     }
});

return false, , / Ok, .

   .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);
+2

Source: https://habr.com/ru/post/1605994/


All Articles