开发者

JQuery Promise question

开发者 https://www.devze.com 2023-04-01 15:46 出处:网络
I\'m currently working on a project which uses many ajax requests to access data from restfull services. Some operations require multiple sequential calls. As soon as i implemented the first of these

I'm currently working on a project which uses many ajax requests to access data from restfull services. Some operations require multiple sequential calls. As soon as i implemented the first of these i ran into race conditions. (calling ajaxCall_1, then ajaxCall_2, which uses the result of ajaxCall_1, but ajaxCall_1 had not returned yet). Of course I could use the .success property, but that does not do the trick for me. Let me explain with a simplified example below. I've got a .js file containing:

function getServerBoolean(){
    $.get('url_1',function(data){return data)});
}

function refreshWidget(){
    $.get('url_2',function(data){
        var serverBoolean = getServerBoolean(); 
        --do some html building here based on boolean returned from server-- }
    );
}

function setServerValue(newValue){
   $.post('url',{key:newValue},function(data){
      // server model has changed, so refresh widget. 
      refreshWidget();
   });

}

Whenever I call setServerValeu('someValue'), the widget needs to refresh itself, but before doing this it needs to know the server boolean value. In this fashion I have many more siutations, so simply giving a callback as a method argument and then calling it in .success() does not do the trick for me.

I stumbled upon the $.when $.then $.done methods, but am not sure how to use these for my situation. Is there anybody who might be able to help me how to set this up?

Thanks in advance!

开发者_开发知识库

Richard


I don't know about $.when $then $done, but functional way of doing this would be to pass callbacks around. It could look like that:

function getServerBoolean(dataCallback){
    $.get('url_1', dataCallback);
}

function refreshWidget(){
    $.get('url_2',function(data){
        getServerBoolean(function(boolValueReturned) {
           //do something with the value
        });
    });
}

Of course there could be numerous way to tweak this, like for example checking (in getServerBoolean) if the argument we got is a function and if not set it to some default callback.

0

精彩评论

暂无评论...
验证码 换一张
取 消