如何让Javascript在继续进行之前等待异步调用? [英] How to get Javascript to wait for an asynchronous call before proceeding?

查看:66
本文介绍了如何让Javascript在继续进行之前等待异步调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工厂,可以去服务器获取一些参考数据.

I have a factory which goes to the server to grab some reference data.

问题是,下面的http get调用是异步的,因此一旦被调用,它将转到下一行.因此,使用下面的代码,它将返回null数据,因为到http调用完成并且我的回调开始时,要复制到data变量,它已经退出了该方法.

The problem through is that the http get call below is asynchronous, so as soon as it's called, it goes to the next line. So with the code below, it'll return data as null because by the time the http call finishes, and my callback starts, to copy to the data variable, it has already exitted the method.

在继续执行下一行之前,如何让它等待回调函数运行?

How can I get it to wait till the callback function has run before proceeding to the next line?

顺便说一下,我在这里使用Angular.

I'm using Angular here by the way.

app.factory('referenceDataFactory', ['$http', function ($http) {
    var factory = [];

    factory.getSports = function () {

        var data;
        $http.get('/Home/GetSports').success(
            function (obj) {
                data = obj;
            });

        return data;    


        // return [{ id: 1, name: 'Volleyball' }, { id: 2, name: 'Football' }, { id: 3, name: 'Tennis' }, { id: 4, name: 'Badminton' }];
    }


    return factory;

}]);

推荐答案

AngularJs中的HTTP API将返回承诺.您应该返回整个promise,并在调用"getSports"的函数中的成功"回调中编写代码.

The http API will in AngularJs will return a promise. You should return that whole promise instead and the have you're code inside the "success" callback back in your functions that calls into "getSports".

这是一个示例.

var app = angular.module('myApp', []);

app.factory('referenceDataFactory', ['$http', function ($http) {
    var factory = [];
    factory.getSports = function () {
        return $http.get('/echo/js/?delay=6&js="test"')
    }

    return factory;
}]);

function HelloCtrl($scope, referenceDataFactory) {
    referenceDataFactory.getSports().success(function (result) {
        $scope.fromFactory = result;
    });
};

这篇关于如何让Javascript在继续进行之前等待异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆