async queue abstraction
This commit is contained in:
27
packages/reacord/library.new/async-queue.ts
Normal file
27
packages/reacord/library.new/async-queue.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
export type AsyncCallback = () => unknown
|
||||
|
||||
export function createAsyncQueue() {
|
||||
const callbacks: AsyncCallback[] = []
|
||||
let promise: Promise<void> | 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 }
|
||||
}
|
||||
@@ -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<void> | 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 }
|
||||
|
||||
Reference in New Issue
Block a user