Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Synchronous api Call in javascript

I Have a method in javascript which call an GET api

var PC;
    function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PC= response;
        }
    });
}

I am setting response in a variable named PC and in another method i am calling this

function PerformTask()
{
GetDetails();
console.log(PC);
}

In GetDetails Method console.log(response); works but in PerformTask() console.log(PC) is undefined

As per my understanding it is a async call and PC is not set yet

How can i make it sync with next statement , ?? as i need value of PC to execute next set of statement

I also tried fetch api call

fetch(Myurl)
        .then(resp => resp.json())
          .then(resp=> setting variable here) ;

But it does not work (work but in async way )

Update 1

return new Promise(function (resolve, reject) {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);;
            resolve(response);
        },
        error: function (err) {
            reject(err);
        }
    });
});

And in Performtask()

GetPropertyDetails()
    .then(function (data) {
        PC= data;
    });
console.log(PC);

But still PC is undefined

like image 595
Saurabh Avatar asked Sep 04 '25 17:09

Saurabh


1 Answers

From success you can call another method which you need a response. As the call is ASYNC so the function will not get the response.

var PC;
function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PC= response;
            // Your next function 
            PerformTask(PC);
        }
    });
}

function PerformTask(pc)
{
    GetDetails();
    console.log(pc);
}

there is another way of doing this but I think that is bad way

$.ajax({
            type: "GET",
            url: Myurl,
            async:false,
            success: function (response) {
                //console.log(response);
                PC= response;
                // Your next function 
                PerformTask(PC);
            }
        });

Using promise => you can use async & await

function asyncCall() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(5)
    }, 2000)
  });
}

(async function() {
  const result = await asyncCall();
  if (result) console.log(result)
})()

Hope this helps you.

like image 175
Kaushik Avatar answered Sep 06 '25 12:09

Kaushik