对于不知道何时完成的异步操作,您应该使用 Promise。一个承诺“代表一个尚未完成的操作,但预计在未来”。(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)
一个示例实现如下:
myApp.factory('myService', function($http) {
    var getData = function() {
        // Angular $http() and then() both return promises themselves 
        return $http({method:"GET", url:"/my/url"}).then(function(result){
            // What we return here is the data that will be accessible 
            // to us after the promise resolves
            return result.data;
        });
    };
    return { getData: getData };
});
function myFunction($scope, myService) {
    var myDataPromise = myService.getData();
    myDataPromise.then(function(result) {  
       // this is only run after getData() resolves
       $scope.data = result;
       console.log("data.name"+$scope.data.name);
    });
}
编辑:关于 Sujoys 的评论,
我需要做什么才能使 myFuction() 调用在 .then() 函数完成执行之前不会返回。
function myFunction($scope, myService) { 
    var myDataPromise = myService.getData(); 
    myDataPromise.then(function(result) { 
         $scope.data = result; 
         console.log("data.name"+$scope.data.name); 
    }); 
    console.log("This will get printed before data.name inside then. And I don't want that."); 
 }
好吧,让我们假设对 getData() 的调用需要 10 秒才能完成。如果该函数在那段时间内没有返回任何内容,它实际上会变成正常的同步代码,并会挂起浏览器直到它完成。
然而,随着承诺立即返回,浏览器可以自由地同时继续处理其他代码。一旦 promise 解决/失败,then() 调用就会被触发。所以这种方式更有意义,即使它可能会使您的代码流更加复杂(毕竟复杂性是异步/并行编程的一个常见问题!)