JSFiddle - React, Tailwind, and code Playground
by rootd
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.js"></script>
<button>Запрос</button>
JavaScript
const state = {
items: [],
users: [],
albums: []
};
const API = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com/'
});
const pending = new Map()
const addPending = config => {
const url = [
config.method,
config.url
].join('&')
config.cancelToken = config.cancelToken || new axios.CancelToken(cancel => {
if (!pending.has(url)) {
pending.set(url, cancel)
}
})
}
const removePending = config => {
const url = [
config.method,
config.url
].join('&')
if (pending.has(url)) {
const cancel = pending.get(url)
cancel(url)
pending.delete(url)
}
}
API.interceptors.request.use(
config => {
removePending(config)
addPending(config)
return config;
},
error => Promise.reject(error)
);
API.interceptors.response.use(
response => {
removePending(response.config);
return response;
},
error => {
if (axios.isCancel(error)) {
} else {
// handle error code
}
return Promise.reject(error)
}
);
async function getPosts () {
const { data } = await API.get('/posts');
state.items = data;
}
async function getUsers () {
const { data } = await API.get('/users');
state.users = data;
}
async function getAlbums () {
const { data } = await API.get('/albums');
state.albums = data;
}
document.querySelector('button').addEventListener('click', () => {
getPosts();
getUsers();
getAlbums();
})
/* getPosts();
getUsers();
getPosts();
getUsers();
getPosts();
getUsers();
getPosts();
getUsers();
getPosts();
getAlbums();
getAlbums();
getAlbums();
getAlbums();
getAlbums();
getUsers();
getPosts(); */
/* (async () => {
await getPosts();
await getUsers();
await getPosts();
await getUsers();
await getPosts();
await getUsers();
await getPosts();
await getUsers();
await getPosts();
})(); */