createPromiseQueue
Create a promise queue. Concurrently run promise, but executing callbacks synchronously in order.
Demo
vue
<script setup lang="ts">
import { createPromiseQueue } from '.'
const val = ref('')
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
async function update() {
val.value = ''
const queue = createPromiseQueue()
queue
.run(() => sleep(1), () => { val.value += '1 done!' })
.run(() => sleep(1000), () => { val.value += '2 done!' })
.run(() => sleep(500), () => { val.value += '3 done!' })
await queue.wait()
}
</script>
<template>
<div>
<button btn @click="update">
Update
</button>
<p>{{ val }}</p>
</div>
</template>Type Declarations
Details
ts
/**
* Create a promise queue. Concurrently run promise, but executing callbacks synchronously in order.
* @example
* ```ts
* const queue1 = createPromiseQueue()
*
* // Run promise and resolver
* queue1
* .run(async () => { await sleep(30) }, () => console.log('3'))
* .run(async () => { await sleep(20) }, () => console.log('2'))
* .run(async () => { await sleep(100) }, () => console.log('ten'))
* await queue1.wait()
* // log `3` on 30ms, log `2` on next moment, log `ten` on 100ms(70ms after log `2`)
*
* // Or
*
* const queue2 = createPromiseQueue()
* const arr = [3, 2, 10]
*
* arr.forEach((v) => {
* queue2.run(async () => { await sleep(v*10); return v }, (val) => console.log(String(val)))
* })
*
* // Will be called after all Promise tasks are resolved
* await queue2.wait()
* // log `3` on 30ms, log `2` on next tick, log `10` on 100ms
* ```
*
* @see {@link https://s3xysteak.github.io/fnclip/functions/promise/createPromiseQueue/}
*/
export declare function createPromiseQueue(): {
run: <T>(task: Callable<Promise<T>>, callback?: (value: T) => Awaitable<any>) => /*elided*/ any;
wait: () => Promise<void>;
};
type Awaitable<T> = T | PromiseLike<T>;
type Callable<T> = T | ((...args: any[]) => T);
export {};