Execution Time overlapse while AJAX JSONP Call

2019-09-04 12:32发布

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条回答
Juvenile、少年°
2楼-- · 2019-09-04 13:00

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/

查看更多
登录 后发表回答