import axios from "axios"; import { message } from "antd"; export default function ajax(url, data = {}, type = 'GET', headers) { return new Promise((resolve, reject) => { let promise; if (type === 'GET'){ promise = axios.get(url, { params: data, headers }) }else if(type === 'POST'){ promise = axios.post(url, data,{headers}) }else if (type === 'PUT') { promise = axios.put(url, data,{headers}) }else if (type === 'DELETE') { promise = axios.delete(url,{ params : data, headers }) } promise.then(response => { resolve(response.data) }).catch(error => { message.error('请求出错了:' + error.message).then(r => {}) }) }) }怎么改成同步axios
时间: 2023-12-12 18:02:34 浏览: 158
ajax-promise-axios代码.zip
不建议将异步请求改为同步请求,因为同步请求会阻塞页面,影响用户体验。但如果你确实需要这样做,可以使用`async/await`将异步请求转换为同步请求,例如:
```
import axios from "axios";
import { message } from "antd";
export default async function ajax(url, data = {}, type = 'GET', headers) {
try {
let response;
if (type === 'GET') {
response = await axios.get(url, {
params: data,
headers
});
} else if (type === 'POST') {
response = await axios.post(url, data, { headers });
} else if (type === 'PUT') {
response = await axios.put(url, data, { headers });
} else if (type === 'DELETE') {
response = await axios.delete(url, {
params: data,
headers
});
}
return response.data;
} catch (error) {
message.error('请求出错了:' + error.message).then(r => {});
throw error;
}
}
```
在这个修改的版本中,我们使用了`async/await`语法来等待异步请求的结果,并将其返回。如果请求出错,我们仍然使用`message.error`方法显示错误消息,并将错误抛出以便上游处理。
阅读全文