Execution Time overlapse while AJAX JSONP Call

穿精又带淫゛_ 提交于 2019-12-12 04:53:41

问题


I have a jsonp ajax call which got executed and returns the data to my main function.

This is done in the success function by calling that.mainfunction(newData);

That means that the main function is called the second time and I think that I'm running therfore in a time/execution problem.

While running in the first iteration newData is empty and gets returned empty to the main function. The main function by this framework I must use. So another control is trying to invoke the getter which is empty. Therefore the control is empty.

Then the second iteration starts. The data is here, the script calls that.mainfunction(newData); and the data gets returned to the main function.

BUT

The time when the second iteration is running it's too late to transfer the data to the control. Because it tried already to get the data.

How can I avoid this time/execution problem? Are there some event bus which I could publish/subscribe while using jquery?

Here is some code:

sap.designstudio.sdk.Component.subclass("component", function() {
var that = this;

this.processDataFromServer = function(){

    function getData(callback){
        $.ajax({
                url: path,
                dataType: 'jsonp',  
                contentType: "application/json",
                success: function(data){
                    callback(data);
                }
            });
    };
    getData(processData);    
    function processData(data){
        this.processDataFromServer(data);
    };
}
this.mainFunction = function(newValue){
  if(typeOf(newValue) == "undefined"{
    this.processDataFromServer();
  } else {
    return newValue;
  }
}

}


回答1:


I see you are using $.ajax, so I believe the cleanest way to approach this challenge is by using jQuery promise/deferred - this will ensure execution at the proper times. I have leveraged promises myself to ensure a clean ajax request / response.

The .promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended.

jQuery Doc

For a thorough walkthrough of the promise/deferred pattern: http://www.danieldemmel.me/blog/2013/03/22/an-introduction-to-jquery-deferred-slash-promise/



来源:https://stackoverflow.com/questions/26804893/execution-time-overlapse-while-ajax-jsonp-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!