Last active
May 16, 2023 17:58
-
-
Save noamr/f5b4944ce667d87d26407f4d285ec707 to your computer and use it in GitHub Desktop.
PendingBeacon on top of fetchLater
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserlandPendingBeacon { | |
#abortController = null; | |
// Let's imagine it's a list of plain objects. | |
#pendingEntries = []; | |
// URL, headers, defer options etc | |
#requestInit; | |
constructor(requestInit) { | |
this.#requestInit = requestInit; | |
this.#pendingEntries = []; | |
} | |
// This will abort an ongoing fetch, and will schedule a new deferred fetch | |
send(entries) { | |
if (this.#abortController) | |
this.#abortController.abort(); | |
this.#pendingEntries = [...this.#pendingEntries, ...entries]; | |
this.#abortController = new AbortController(); | |
fetchLater({signal: this.#abortController.signal, body: JSON.stringify(this.#pendingEntries), ...this.#requestInit}) | |
.then(() => { | |
this.#abortController = null; | |
this.#pendingEntries = []; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment