How to get result of the last then function in chain of promises when making resolve call with Angular $q?

340 Views Asked by At

The problem I am experiencing is a bit hard to explain, and I might getting (Angular) promises wrong, but still...

I am trying to handle the following situation nicely. In general, let's say I want to have my Angular dialogService to provide a confirm method, which would return a promise resolved on clicking yes button, it means when the confirm actually succeeded. However, I want the dialog would stay open until the internal async operation--which would be executed on yes confirmation--finishes. And if it's finishes successfully, then the dialog should close, otherwise stay open.

In code that would be (perfectly) looking like this:

the outer code:

    dialogService.confirm('title', 'message').then =>
        return myLongLastingOperationReturningPromise()

the confirm method implementation something like this:

    def = $q.defer()

    dialog = ngDialog.open(...)
    // closePromise or any other custom local promise
    dialog.closePromise.then =>
        // this is fake, but how can I achieve this?
        result = def.resolve('closeRequest');
        if(typeof result.then == 'function') {
            result.then =>
                // continue closing the dialog
        } else if (result === false) {
            // just do nothing
        } else {
            // closing the dialog
        }

in other words, is there any way to obtain the result of the last then method in the promises chain on/after calling resolve?

1

There are 1 best solutions below

1
huan feng On

You should execute the confirm after the API has successfully returned.

e.g. Click 'yes' button will execute method YesHandler:

//$scope is the ngDialog scope here
$scope.YesHandler = function () {
  myLongLastingOperationReturningPromise().then(function(data) {
    //Execute confirm method after API returned
    $scope.confirm(data);
  })
}

In caller:

modalInstance = ngDialog.openConfirm({
                    template: 'xxx.tpl.html',
                    scope: $scope,
                    controller: 'xxxCtrl'
                    });

modalInstance.then(function (data) {
  //This data is returned from confirm
});