From 4db32ddbbbd66d0c1b50b64a2cca0d30c200fcfa Mon Sep 17 00:00:00 2001 From: itsMapleLeaf <19603573+itsMapleLeaf@users.noreply.github.com> Date: Sat, 23 Jul 2022 18:39:17 -0500 Subject: [PATCH] async queue abstraction --- packages/reacord/library.new/async-queue.ts | 27 ++++++++++++++++ packages/reacord/library.new/discord-js.ts | 34 ++++----------------- 2 files changed, 33 insertions(+), 28 deletions(-) create mode 100644 packages/reacord/library.new/async-queue.ts diff --git a/packages/reacord/library.new/async-queue.ts b/packages/reacord/library.new/async-queue.ts new file mode 100644 index 0000000..3c3b96f --- /dev/null +++ b/packages/reacord/library.new/async-queue.ts @@ -0,0 +1,27 @@ +export type AsyncCallback = () => unknown + +export function createAsyncQueue() { + const callbacks: AsyncCallback[] = [] + let promise: Promise | undefined + + async function add(callback: AsyncCallback) { + callbacks.push(callback) + if (promise) return promise + + promise = runQueue() + try { + await promise + } finally { + promise = undefined + } + } + + async function runQueue() { + let callback: AsyncCallback | undefined + while ((callback = callbacks.shift())) { + await callback() + } + } + + return { add } +} diff --git a/packages/reacord/library.new/discord-js.ts b/packages/reacord/library.new/discord-js.ts index 6ddf923..e1e00a0 100644 --- a/packages/reacord/library.new/discord-js.ts +++ b/packages/reacord/library.new/discord-js.ts @@ -7,6 +7,7 @@ import type { TextBasedChannel, } from "discord.js" import type { ReactNode } from "react" +import { createAsyncQueue } from "./async-queue" import type { ReacordOptions } from "./reacord" import { createReacordInstanceManager } from "./reacord" @@ -34,43 +35,20 @@ export function createReacordDiscordJs( } function createMessageUpdater() { - type UpdatePayload = { - options: MessageOptions & MessageEditOptions - channel: TextBasedChannel - } - let message: Message | undefined - - const queue: UpdatePayload[] = [] - let queuePromise: Promise | undefined + const queue = createAsyncQueue() async function update( options: MessageOptions & MessageEditOptions, channel: TextBasedChannel, ) { - queue.push({ options, channel }) - - if (queuePromise) { - return queuePromise - } - - queuePromise = runQueue() - try { - await queuePromise - } finally { - queuePromise = undefined - } - } - - async function runQueue() { - let payload: UpdatePayload | undefined - while ((payload = queue.shift())) { + return queue.add(async () => { if (message) { - await message.edit(payload.options) + await message.edit(options) } else { - message = await payload.channel.send(payload.options) + message = await channel.send(options) } - } + }) } return { update }