JavaScript 异步请求与 Web 存储 API 全解析
1. 异步请求与 Promise
在 JavaScript 中,异步请求是常见的操作。我们可以使用 Promise 来处理异步请求。以下是一个简单的异步请求示例:
// If the request fails, reject the Promise with the
// error that was emitted.
request.addEventListener('error', error => {
reject(error);
});
// Set the target URL and send the request.
request.open('GET', url);
request.send();
这里,我们为请求添加了错误监听事件。当请求失败时,会通过 reject 函数将错误信息传递出去。然后设置请求的目标 URL 并发送请求。
下面是使用封装好的 loadJSON 函数的示例:
// Using .then
loadJSON('/api/users/1').then(user => {
console.log('Got user:', user);
})
// Using await
const user = await loadJSON('/api/users/1');
console.log('Got user:',
超级会员免费看
订阅专栏 解锁全文
1338

被折叠的 条评论
为什么被折叠?



