javascriptjqueryfunctionasync-await.post

run functions one by one after each other like async but without async


one of them will connect to php page and get some data and other one of my functions will change some html codes with new data which collected by first function.

for example this is my code :

var $data;
firstFunction(){
    $.post("index.php",{},function(data){$data=data;});
}
secondFunction(){
    $("body").empty().append($data);
}
firstFunction();
secondFunction();

So in the code in upside if we run this its will start collecting data but before finish collecting data its will run second function which is incorrect and it have to run second function after first function finished some thing like this :

$.when(firstFunction()).done(function(){secondFunction();});

But its not works too and i know there is something called async but i wanna know is there anyway else to do this without changing functions and if its possible give me example with async too pls.

And also i don't want to change functions i mean i know that i can do like this :

var $data;
firstFunction(){
    $.post("index.php",{},function(data){$data=data;secondFunction();});
}
secondFunction(){
    $("body").empty().append($data);
}
firstFunction();

As you can see in the new code second function will run after first permission finish it job but i can't and i don't want to do like this i want something like async but in other way if its possible because i have many functions and its will take long time to change theme.

Thanks a lot.


Solution

  • You might want to consider using a library like Axios which is promise based, you can use async/await with this method as well as promise chaining. You can bring this into your application using either script tag with a CDN or via NPM/Yarn.

    https://github.com/axios/axios

    Here is an example with async await:

    async function getData(){
    
     async function getPosts(){
      try {
       const response = await 
       axios.get('https://jsonplaceholder.typicode.com/posts/1');
        return response
       } catch (error) {
        console.error(error);
       }
     }
    
     var Posts = await getPosts();
     document.getElementById('posts').textContent = JSON.stringify(Posts.data);
    
     async function getComments(){
      try {
       const response = await 
       axios.get('https://jsonplaceholder.typicode.com/comments/1');
        return response
       } catch (error) {
       console.error(error);
       } 
     }
    
    
      var Comments = await getComments();
      document.getElementById('comments').textContent = 
      JSON.stringify(Comments.data);
    

    }

    https://jsfiddle.net/Lm2c6r40/