使用回调函数或Promise来处理异步请求。下面是使用Promise的示例代码:
function fetchData() {
return new Promise(function(resolve, reject) {
$.ajax({
url: 'http://example.com/data',
success: function(data) {
resolve(data);
},
error: function() {
reject(new Error('Failed to fetch data'));
}
});
});
}
function processData() {
fetchData().then(function(data) {
// handle data here
console.log(data);
}).catch(function(error) {
// handle error here
console.log(error);
});
}
processData();
在上面的代码中,fetchData函数返回一个Promise对象,用于处理异步请求。processData函数调用fetchData函数来获取数据,并使用then方法来处理返回的数据,catch方法来处理错误情况。这种方式能够确保函数在数据返回之后再执行,避免了数据延迟返回的问题。