js uses callback function or Promise object
Callback
is a common method used to execute specific code after an Ajax request completes. Callback functions are usually passed as parameters to Ajax request functions and are invoked as soon as the request is complete.
For example:
<script>
function loadData1(callback) {
// code for first Ajax request
// after the request is complete, call the callback function
callback();
}
function loadData2() {
// code for second Ajax request
}
loadData1(loadData2);
</script>
Promise object
is a new feature in ES6 that can be used to handle asynchronous requests. A Promise object is an object that can return a result in two states (success or failure) after the request is completed.
For example:
<script>
function loadData1() {
return new Promise((resolve, reject) => {
// code for first Ajax request
// if the request is successful, call resolve()
resolve();
// if the request fails, call reject()
// reject();
});
}
function loadData2() {
// code for second Ajax request
}
loadData1()
.then(loadData2)
.catch(error => {
// handle the error
});
</script>
Using callback functions and Promise objects are both valid approaches, depending on your needs and preferences which one to use.