33 lines
1.4 KiB
JavaScript
33 lines
1.4 KiB
JavaScript
/* Bounded requests; mutation requests are never retried automatically. */
|
|
(function () {
|
|
'use strict';
|
|
const pending = new Map();
|
|
async function request(url, options = {}) {
|
|
const controller = new AbortController();
|
|
const abort = () => controller.abort();
|
|
if (options.signal?.aborted) controller.abort();
|
|
else options.signal?.addEventListener('abort', abort, { once: true });
|
|
const timer = setTimeout(abort, options.timeout || 15000);
|
|
try {
|
|
return await fetch(url, { ...options, signal: controller.signal });
|
|
} catch (error) {
|
|
if (error.name === 'AbortError') throw new Error('请求超时或已取消,请刷新状态后重试');
|
|
throw error;
|
|
} finally {
|
|
clearTimeout(timer);
|
|
options.signal?.removeEventListener('abort', abort);
|
|
}
|
|
}
|
|
async function run(key, button, action) {
|
|
if (pending.has(key)) return pending.get(key);
|
|
if (button) { button.disabled = true; button.setAttribute('aria-busy', 'true'); }
|
|
const task = Promise.resolve().then(action).finally(() => {
|
|
pending.delete(key);
|
|
if (button) { button.disabled = false; button.removeAttribute('aria-busy'); }
|
|
});
|
|
pending.set(key, task);
|
|
return task;
|
|
}
|
|
window.AppAPI = { fetch: request, run };
|
|
})();
|