-1

I have a problem while i am getting data from api in a function, it is collecting data late and not waiting for function to complete execution and skipping it and moving forward for next line execution.

function getQ(mid){
                $.ajax({
                url : "http://localhost:8080/modules/"+ mid ,
                type : "get"  , 
                dataType : "json" , 
                success : function( response , status , http ) {
                    $.each( response , function( index , item ){
                        var s =  item.q;
                        var v = JSON.stringify(item.qIDfromDB)
                        console.log(str +": " );
                        dbAnswers.push({ text: s, value: v});
                    }); 
                    console.log(dbAnswers);
                },
                error : function( http , status , error ) {
                    alert( 'Some Error Occured : ' + error );
                }           
               });              
             }
  • 1
    You will need to post your code. – Johnathan Barclay Jun 05 '20 at 10:28
  • using async await or promise resolve to make code synchronous – Vương Vũ Nguyễn Jun 05 '20 at 10:29
  • 1
    @VươngVũNguyễn using async/await doesn't make the code synchronous, it just makes the syntax and code flow appear to be more linear. This is not the same thing. – ADyson Jun 05 '20 at 10:34
  • The result `something_but_not_really` is only available in the success-function. If you want `doAjax` to "return" something, you need to respect the fact that `doAjax` needs to become asynchronous from the callers point of view, too (e.g. by returning a Promise, or calling a given callback function). You should learn [more about asynchronous JavaScript first](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous). – Sebastian B. Jun 05 '20 at 10:38

2 Answers2

1

You may use async/await like following way:

function getData(ajaxurl) { 
  return $.ajax({
    url: ajaxurl,
    type: 'GET',
  });
};

async function test() {
  try {
    const res = await getData('https://api.icndb.com/jokes/random')
    console.log(res)
  } catch(err) {
    console.log(err);
  }
}

test();
Mehadi Hassan
  • 1,160
  • 1
  • 13
  • 33
0

Just use async/await

(async () => {
  try {
    const response = await fetch('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
    const json = await response.json()
  } catch (error) {
    console.log(error.response.body);
  }
})();