在继续之前等待先前的提取完成中止

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'),输出当然是...

STARTED thing1
STARTED thing2
ERRORED thing1
FINALLY'D thing1
FINALLY'D thing2

...因为 requestThing 会立即触发新的提取,而中止是异步发生的。有什么优雅的方法可以在继续之前等待先前的提取完成中止吗?此外,当然,...

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();
}