写一个proimse封装
时间: 2024-05-06 13:21:30 浏览: 12
异步请求的例子。
好的,这是一个使用Promise封装异步请求的例子:
```javascript
function makeRequest(url, method) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = () => {
reject({
status: xhr.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
makeRequest('https://jsonplaceholder.typicode.com/todos/1', 'GET')
.then(response => {
console.log('Response:', response);
})
.catch(error => {
console.error('Error:', error);
});
```
这个例子使用了XMLHttpRequest对象来发起异步请求,并使用Promise封装了请求过程。如果请求成功,则通过resolve方法返回响应数据,如果请求失败,则通过reject方法返回错误信息。在使用时,我们可以通过.then()方法获取成功时的响应数据,通过.catch()方法捕获错误信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![html](https://img-home.csdnimg.cn/images/20210720083451.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)