I have a few Ajax requests which will be executed sequentially.
$.ajax({
url: 'https://dummyjson.com/products/1',
success: (res) => {
console.log(1, res);
$.ajax({
url: 'https://dummyjson.com/carts/1',
success: (res) => {
console.log(2, res);
$.ajax({
url: 'https://dummyjson.com/posts/1',
success: (res) => {
console.log(3, res);
$.ajax({
url: 'https://dummyjson.com/comments/1',
success: (res) => {
console.log(4, res);
}
});
}
});
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I know it can be done with new Promise((resolve,reject)=>{})
with async & await
function, but I want to use the chaining method for calling AJAX sequentially like this.
ajax1.then((res)=>ajax2).then((res)=>ajax3).then((res)=>ajax4).catch(e => e);
How can implement this with jQuery?
2
Answers
I create a custom function called
ajax
for chaining method implementation.Hope this will be helpful.