js使用回调函数或Promise对象
回调函数
是一种常见的方法,用于在Ajax请求完成后执行特定的代码。回调函数通常作为参数传递给Ajax请求函数,并在请求完成后立即调用。
例如:
<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对象
是ES6中的一种新特性,它可以用于处理异步请求。Promise对象是一个对象,可以在请求完成后以两种状态(成功或失败)返回结果。
例如:
<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>
使用回调函数和Promise对象都是有效的方法,具体使用哪种方法取决于您的需求和偏好。