如何让我的javascript函数等待AJAX​​调用的结果?

时间:2014-12-10 00:29:44

标签: javascript ajax callback

我正在编写一个APIService类来帮助我为我的Web应用程序提供AJAX请求的标准化方法。 httpRequest函数表达式正常工作。当我第二次调用ApiService.call时,它可以正常工作,因为已经设置了端点。顺便说一句 - 我将它定义为静态类,以便可以在不实例化的情况下引用它。

我在ApiService中遇到调用方法的问题。具体来说,当我调用ApiService.setEndpoints时,在进行httpRequest时,尚未设置ApiService.endpoints.store_get(运行setEndpoint方法时创建的默认端点)。

我知道如果需要设置数据,你应该传递一个回调,但是,我不知道在这种情况下如何最好地做到这一点。

var ApiService = 
{
    endpoints: {
    },

    ENUMERATE_ENDPOINT:'/apis/abc/0.1/json/Resource/Enumerate/init',

    init:function()
    {
    },

    setEndpoints:function()
    {
        try {
            new httpRequest(ApiService.ENUMERATE_ENDPOINT,'','GET',ApiService.constructEndpoint,true);
        } catch(e) {
            console.log('Error making AJAX call to set API endpoints');
            console.log('Error message: ' + e.message)
        }
    },

    constructEndpoint:function(data)
    {
        var json = JSON.parse(data);
        if (json.hasOwnProperty('success') && (json.success == 'TRUE' )) {
            // Sets the api endpoints
            for (endpoint in json.payload.api_endpoints) {
                ApiService.endpoints[endpoint] = json.payload.api_domains.api_root_url.slice(json.payload.api_domains.api_root_url.indexOf('apis')) 
                                                + json.payload.api_endpoints[endpoint];
            }               
        }
    },

    call:function(params, callback, endpoint_string)
    {
        endpoint_string = endpoint_string || undefined;

        try {
            if (typeof endpoint_string !== "undefined") {
                new httpRequest(endpoint_string, params, 'POST', callback, true);
            } else {        
                ApiService.setEndpoints();
                new httpRequest(ApiService.endpoints.store_get, params, 'POST', callback, true);
            }
        } catch(e) {
            console.log('Error making AJAX call to API endpoints');
            console.log('Error message: ' + e.message);
        }
    }
}

var httpRequest = function(url,params,method,callback,async)

BTW - 我知道我可以在setEndpoints函数中将async设置为false,但我不想降低api的性能

0 个答案:

没有答案
相关问题