I have a function and its have nested two ajax call. I want to return a value inside from second ajax call when ajax call is successed. i think because function ending but the ajaxs call still not end. But i didn’t solve it.
I prepared a example code below:
var patato = function(){
$.ajax({
type: 'POST',
url: 'https://jsonplaceholder.typicode.com/posts',
dataType: 'json',
data: {
title: 'foo',
body: 'bar',
userId: 1,
},
success:function(res){
console.log("Work 1")
$.ajax({
type: 'POST',
url: 'https://jsonplaceholder.typicode.com/posts',
dataType: 'json',
data: {
title: 'foo',
body: 'bar',
userId: 1,
},
success:function(res){
console.log("Work 2")
return true;
}
})
}
})
console.log("Çalıştı 3")
}
var patatos = patato();
if(patatos) {
console.log("Patato true")
}else{
console.log("Patato false")
}
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
3
Answers
Your function should return a promise since you are doing some async work (fetching).
Also I strongly recommend to use
async/await
to simplify logic and improve readability/maintainability:First thing that I wanted to mention is that it will not make much sense to make sequential requests if you second request don’t need the response from the first one. On that note, I will assume you have a use case that requires two API call executed one after the other.
Here you have two options: use callbacks or
async/await
syntax.Here you can find a good example of the usage of both: How to return an Ajax result using async/await?
For your particular example here’s how you could do this with callbacks:
Or you could use
async/await
syntax as well (IMO this is easier to follow than the callback one):You can also run both AJAX jobs in parallel if the output of the first job is not required for the second one: