【问题标题】:How to get result of the last then function in chain of promises when making resolve call with Angular $q?使用 Angular $q 进行解析调用时,如何获得承诺链中最后一个 then 函数的结果?
【发布时间】:2017-10-11 18:07:30
【问题描述】:

我遇到的问题有点难以解释,我可能会得到(Angular)承诺错误,但仍然......

我正在尝试很好地处理以下情况。 一般来说,假设我想让我的 Angular dialogService 提供一个 confirm 方法,该方法将在单击 yes 按钮时返回一个已解决的承诺,这意味着当确认实际成功时。但是,我希望对话框保持打开状态,直到内部async 操作——这将在yes 确认上执行——完成。如果成功完成,则对话框应关闭,否则保持打开状态。

在(完美)看起来像这样的代码中:

外码:

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

confirm 方法实现如下:

    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
        }

换句话说,有没有办法在调用resolve时/之后获取promise链中最后一个then方法的结果?

【问题讨论】:

    标签: angularjs angular-promise deferred ng-dialog


    【解决方案1】:

    您应该在 API 成功返回后执行确认。

    例如 单击“是”按钮将执行方法 YesHandler:

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

    在调用者中:

    modalInstance = ngDialog.openConfirm({
                        template: 'xxx.tpl.html',
                        scope: $scope,
                        controller: 'xxxCtrl'
                        });
    
    modalInstance.then(function (data) {
      //This data is returned from confirm
    });
    

    【讨论】:

    • 嗨,你检查过这个答案吗?
    猜你喜欢
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 2017-04-06
    相关资源
    最近更新 更多