简体   繁体   中英

Make Asynchronous method Synchronous javascript

I have some JavaScript code which pulls data out of 2 sources.

1st source is local web storage

2nd source is AJAX request.

The condition is simple :

    function getMyData(){
    if (window.localStorage['myData'] != null)
    {
        return window.localStorage['myData'];
    }
    else
    {
        networkTools.ajax("geyMyData", function (data)
        {
            return data;
        })
    }}

But the problem is that AJAX is async process and I don't want the code to continue until getMyData() return something.

I know that I can use callbacks, but would like just to wait until this function returns something and then continue the execution. (Not only for this case, but for general knowledge.)

Is that possible?

Use callback

    function getMyData(callback){
        if (window.localStorage['myData'] != null)
        {
            callback(window.localStorage['myData'];)
        }
        else
        {
            networkTools.ajax("geyMyData", function (data)
            {
                callback(data);
            })
        }
  }

How to call getMyData

getMyData(function(data){
      //your code
});

Or you can make your ajax request as a synchronous request.

The best way to do this is with a callback function.

You don't want your JavaScript to block for things like network requests because your web page would become completely unresponsive.

This is how you would do it:

function getMyData(callback){
    if (window.localStorage['myData'] != null)
    {
        return window.localStorage['myData'];
    }
    else
    {
        networkTools.ajax("geyMyData", function (data)
        {
            callback(data);
        });
    }
}

The best option would be to call getMyData with a callback and break your functions up into caller -> getMyData -> callback. it is possible to do a synchronous request but you'd better not because it locks up the browser until the call is done.

function gotData(data){
  console.log("got data:",data);
}
function someFunction(){
 ...
 getMyData(gotData);
}
    function getMyData(callback){
    if (window.localStorage['myData'] != null)
    {
        callback(window.localStorage['myData']);
    }
    else
    {
        networkTools.ajax("geyMyData", function (data)
        {
            callback(data);
        })
    }}

I did not include how to do a synchronous request because it's bad to do so but if you really want to do it than how to it can be found anywhere (like MDN developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM