简体   繁体   English

完成函数调用后应执行以下代码

[英]After complete execution of function call should execute following code

     $scope.selectSample = function (name) {
        $scope.getSample(); //GET REQUEST

        /*SOME CODE HERE*/

    };

Here, selectSample is click event ,First it should execute complete cycle of getSample() and THEN ONLY execute following code. 在这里, selectSample是click事件,首先它应该执行getSample()完整周期,然后仅执行以下代码。 Now, before completion of getSample() the other part of code is getting executed. 现在,在完成getSample()之前,将执行另一部分代码。 Any solution on this? 有什么解决办法吗?

It will happen as javascript is asynchronous . 这将因为javascript是异步的而发生。 There are various ways to handle this like : 1) Promises 2) Callbacks 3) Closures 有多种处理方式,例如:1)承诺2)回调3)关闭

I will give an example : 我举一个例子:

Example by Promise in your case: 在您的情况下以Promise为例:

 var app = angular.module('myAngularApp', []); app.controller('test', function ($scope,$q) { var okToGreet= function(name){ if(name=='Robin Hood'){ return true; }else{ return false; } } $scope.getSample= function(name) { var deferred = $q.defer(); setTimeout(function() { deferred.notify('About to greet ' + name + '.'); if (okToGreet(name)) { deferred.resolve('Hello, ' + name + '!'); } else { deferred.reject('Greeting ' + name + ' is not allowed.'); } }, 1000); return deferred.promise; } $scope.selectSample = function (name) { //GET REQUEST var promise = $scope.getSample('Robin Hood'); promise.then(function(greeting) { alert('Success: ' + greeting); }, function(reason) { alert('Failed: ' + reason); }, function(update) { alert('Got notification: ' + update); }); /*SOME CODE HERE*/ }; $scope.selectSample(); }); 
 <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body ng-app="myAngularApp"> <div ng-controller="test"> </div> </body> </html> 

Example by closure : 闭包示例:

var rankings = ['A', 'B', 'C'];
 for (var i = 0, len = rankings.length; i < len; i++) {
   setTimeout(function() {
      console.log(i, rankings[i]);
   }, i * 1000);
 }

The idea is to print every name from the rankings array together with its index. 想法是打印排名数组中的每个名称及其索引。 To make the code asynchronous every print is delayed by one second from its predecessor. 为了使代码异步,每次打印都比其前一打印延迟一秒钟。 The output we get is, however, different than what we expected it to be 但是,我们得到的输出与我们预期的不同

Output : 输出:

 3 undefined
 3 undefined
 3 undefined

As you can see, by the time the asynchronous block is executed, the loop is already ended, so the value of variable i is the one that stops the loop (3). 如您所见,在执行异步块时,循环已经结束,因此变量i的值就是停止循环的值(3)。 How to prevent this behavior? 如何预防这种行为? The answer are closures, one of the most powerful features of Javascript; 答案是闭包,这是Javascript最强大的功能之一。 a closure can be seen as a retained scope for Javascript, a function that can have its own variables together with an environment where those variables are binded. 闭包可以看作是Javascript的保留范围,该函数可以具有自己的变量以及绑定了这些变量的环境。

Let's fix the previous example using closures: 让我们使用闭包修复前面的示例:

var rankings = ['alice', 'bob', 'eve'];
for (var i = 0, len = rankings.length; i < len; i++) {
  (function(i) {
    setTimeout(function() {
      console.log(i, rankings[i]);
    }, i * 1000);
  })(i);
}

As you can see the setTimeout function is wrapped within a closure that has an i argument, whose value is passed at the end of closure definition and corresponds to the loop varialbe i. 如您所见,setTimeout函数包装在一个带有i参数的闭包中,该闭包的值在闭包定义的末尾传递,并且与循环变量i对应。 The output we get is the correct one: 我们得到的输出是正确的:

0 'A'
1 'B'
2 'C'

I hope i was able to explain your issue. 希望我能解释您的问题。

Call GET request as a promise instead of $scope.function(), we must use $scope only for the functions interacting with view. 将GET请求作为一个承诺而不是$ scope.function()调用,我们必须仅将$ scope用于与视图交互的函数。

$scope.selectSample = function (name) {
 /* call GET request as promise instead of $scope */
    myService.getSample(uri).then(function(result){  // $scope.getSample(); GET REQUEST
          // after promise returns write your code
         /*SOME CODE HERE*/
    });
};

myService.getSample = function(uri) {
    return $http.get(uri).then(function (response) {
        return response.data; // return promise
    });
};

try this 尝试这个

$scope.selectSample = function (name) {
        $scope.getSample(); //GET REQUEST
    };

$scope.getSample = function (){
    $scope.yoursomecode()
}

$scope.yoursomecode () {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM