异步的使用场景有哪些
# 异步的使用场景有哪些
# 1. AJAX 请求:
// 使用 XMLHttpRequest 发送异步请求
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
# 2. 定时器:
// 使用 setTimeout 延迟执行代码
console.log('开始执行异步操作');
setTimeout(function() {
console.log('异步操作完成');
}, 2000);
console.log('异步操作执行完毕前');
// 使用 setInterval 定期执行操作
setInterval(function() {
console.log('定期执行操作');
}, 1000);
# 3. Promise:
// 使用 Promise 处理异步操作
function fetchData() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('数据加载成功');
}, 2000);
});
}
fetchData()
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.error(error);
});
# 4. 时间监听:
// 添加点击事件监听器
var button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
console.log('按钮被点击了');
});
// 添加键盘事件监听器
document.addEventListener('keydown', function(event) {
console.log('按下了键盘按键:', event.key);
});
# 5. 文件读取:
// 使用 FileReader 异步读取文件
var fileInput = document.getElementById('myFileInput');
fileInput.addEventListener('change', function(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
console.log('文件内容:', e.target.result);
};
reader.readAsText(file);
});