0

Is there any alternative code of jquery ajax async false ?

I should code like below:

func1(){
    var result = false;
    $.getJSON("URL", function(data){
        result = data;
    });

    return result;
}

How about adding done() method after $.getJSON()? then the code flows as func1() -> getJSON() -> done() -> func1() -> return ?

Any suggestion?

Pedram
  • 15,766
  • 10
  • 44
  • 73
  • Callbacks, promises, async/await. plenty of tutorials for all of them. You can't return data from inside an async function like getJSON without making it sync by using the async = false flag. – Shilly Dec 20 '17 at 12:29
  • 1
    there is no alternative if you want `func1` to return a value synchronously - which you should avoid anyway – Jaromanda X Dec 20 '17 at 12:30
  • I see.... then I have to approach another way.. –  Dec 20 '17 at 12:32
  • Functions you write should be non blocking, that means they have to return a value immediately so you can't wait for a network request to finish so you can return the result. You can return a promise of the network result. It is explained in more detail [here](https://stackoverflow.com/a/47678417/1641941). – HMR Dec 20 '17 at 15:22
  • @HMR thank you really! that is an alternative way that I want. I didn't know about async function and promise. Now I am digging in promise reference. :) –  Dec 20 '17 at 19:49

0 Answers0