使用 Promise 实现异步操作,当异步操作完成时,Promise 对象会返回执行结果或错误信息。
示例代码:
function getData(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
}
xhr.onerror = function() {
reject(new Error(xhr.statusText));
}
xhr.send();
});
}
getData('https://example.com/api/data')
.then(data => console.log(data))
.catch(error => console.error(error));
使用 Fetch API 发起异步请求,它返回一个 Promise 对象,当数据到达时会跳转到 .then() 方法。
示例代码:
fetch('https://example.com/api/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
使用 Async/await 可以使用异步操作并以同步代码的方式进行操作。
示例代码:
async function getData() {
const response = await fetch('https://example.com/api/data');
const data = await response.text();
return data;
}
getData()
.then(data => console.log(data))
.catch(error => console.error(error));