angularjs控制器中的顺序执行

时间:2017-03-08 09:13:12

标签: javascript angularjs

我在角度控制器中有调用服务的方法;此方法应基于服务响应。

但我不知道为什么方法会在合适的时间调用。



$scope.UpdateSelected = function () {
    $rootScope.showConfirmModal().result.then(function () {
        var selectedItems = _.filter($scope.Options, { Selected: true });
        var error = 0

        for (var i = 0 ; i < selectedItems.length; i++) {
            InvalidOptionsFactory.UpdateOptions(selectedItems[i].Id).then(function (res) {
                if (res.data.error) {
                    error++;
                }
            });
        }
            if (error == 0) {
                toastr.success($rootScope.GetString('GENERIC_SAVE_SUCCSS_MSG'));
            }

            else if (error == selectedItems.length) {
                $rootScope.showMessageModal($rootScope.GetString('UPDATE_STATUS_FAILED'), 'sm');
            }
            else {
                var message = hasError + $rootScope.GetString('UPDATE_STATUS_PARTIALLY_FAILED');
                toastr.success(message);
            }
            fetchSearchedData();
    });
    };
&#13;
&#13;
&#13;

我现在不知道为什么它会直接转到if语句并执行它然后调用服务

1 个答案:

答案 0 :(得分:1)

这是因为InvalidOptionsFactory.UpdateOptions(selectedItems[i].Id)方法是异步的。这就是让应用程序不等待服务调用的原因,它首先运行if (error == 0)语句(请参阅下面的代码片段以获取证明)。在这里学习异步方法:https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascript

你可以将你的代码变成这样的代码(p.s.我用babel作为预处理器):

$scope.UpdateSelected = function () {
  $rootScope.showConfirmModal().result.then(function () {
    var selectedItems = _.filter($scope.Options, { Selected: true });
    checkForError(selectedItems).then(error => {
      if (error == 0) {
        toastr.success($rootScope.GetString('GENERIC_SAVE_SUCCSS_MSG'));
      } else if (error == selectedItems.length) {
        $rootScope.showMessageModal($rootScope.GetString('UPDATE_STATUS_FAILED'), 'sm');
      } else {
        var message = hasError + $rootScope.GetString('UPDATE_STATUS_PARTIALLY_FAILED');
        toastr.success(message);
      };

      fetchSearchedData();
    });
  });
};

function checkForError(selectedItems): Promise<number> {
  return new Promise(resolve => {
    var error = 0;
    for (var i = 0 ; i < selectedItems.length; i++) {
      InvalidOptionsFactory.UpdateOptions(selectedItems[i].Id).then(function (res) {
        if (res.data.error) {
          error++;
        };
      });
    };

    resolve(error); 
  });
}

function asyncFunc(): Promise<void> {
  return new Promise(resolve => {
    console.log("this is async");
    resolve();
  });
}

asyncFunc().then(() => {
  console.log("async function ended");
});

console.log("this will be called before async function ended");