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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With