最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Making Synchronous api Call in javascript - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited May 28, 2019 at 3:54 Saurabh asked May 28, 2019 at 3:34 SaurabhSaurabh 1,6317 gold badges25 silver badges43 bronze badges 4
  • in success call the method PerformTask. – Kaushik Commented May 28, 2019 at 3:36
  • @Kaushik , , need value of PC inside PerformTask reason : there will be around 5 ,6 method in same manner inside PerformTask for initialization purpose , – Saurabh Commented May 28, 2019 at 3:38
  • You can call the method with param pc and further you can use that. another approach is in ajax call you can make async=false. and btw I've not down voted. LOL. – Kaushik Commented May 28, 2019 at 3:41
  • Possible duplicate of How do I return the response from an asynchronous call? – VLAZ Commented May 28, 2019 at 4:35
Add a ment  | 

2 Answers 2

Reset to default 2

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.

The better option is to call the PerformTask() function inside the ajax success and pass the result to PerformTask function. ie,

   function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PerformTask(response);
        }
    });
}
发布评论

评论列表(0)

  1. 暂无评论