[英]Wait for prior fetch to finish aborting before proceeding
現在我的代碼基本上是:
var loadingIndicator = /* Reference to UI component */,
output = /* Reference to UI component */,
abortController;
function onThingRequested(thing) {
abortController?.abort();
requestThing(thing);
}
async function requestThing(thing) {
abortController = new AbortController();
output.innerText = '';
loadingIndicator.show();
try {
console.log(`STARTING ${thing}`);
// For the sake of brevity of the example, assume `thing` is safe to put here.
var thingRes = await fetch(`/example?thing=${thing}`, { signal: abortController.signal });
output.innerText = await thingRes.text();
} catch (err) {
console.log(`ERRORED ${thing}`);
output.innerText = err;
} finally {
console.log(`FINALLY'D ${thing}`);
loadingIndicator.hide();
}
}
如果我觸發onThingRequested('thing1')
,然后在加載之前觸發onThingRequested('thing2')
,那么 output 當然是......
STARTED thing1
STARTED thing2
ERRORED thing1
FINALLY'D thing1
FINALLY'D thing2
...因為requestThing
會立即觸發新的 fetch,而中止是異步發生的。 有什么優雅的方法可以等待先前的 fetch 在繼續之前完成中止? 此外,當然,... hacky 感覺的解決方法
function onThingRequested(thing) {
abortController?.abort();
setTimeout(() => requestThing(thing), 1);
}
在再次調用requestThing
之前,您可以使用abort事件檢查獲取請求是否已中止。
function onThingRequested(thing) {
if (!abortController) {
requestThing(thing);
return;
}
abortController.signal.onabort = () => {
requestThing(thing);
};
abortController.abort();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.