From d19880e0c918ada8a9d06bcbf135a6a43ed2e82b Mon Sep 17 00:00:00 2001 From: Asher Gomez Date: Fri, 3 Nov 2023 09:00:35 +1100 Subject: [PATCH] refactor: use `Array.fromAsync()` (#639) [Deno 1.38](https://deno.com/blog/v1.38#v8-120) now supports [`Array.fromAsync()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync). --- tasks/db_dump.ts | 7 ++++--- utils/db.ts | 4 +--- utils/posts.ts | 16 +++++++--------- 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/tasks/db_dump.ts b/tasks/db_dump.ts index c5a42c729..d9ed1cb6e 100644 --- a/tasks/db_dump.ts +++ b/tasks/db_dump.ts @@ -15,9 +15,10 @@ function replacer(_key: unknown, value: unknown) { return typeof value === "bigint" ? value.toString() : value; } -const iter = kv.list({ prefix: [] }); -const items = []; -for await (const { key, value } of iter) items.push({ key, value }); +const items = await Array.fromAsync( + kv.list({ prefix: [] }), + ({ key, value }) => ({ key, value }), +); console.log(JSON.stringify(items, replacer, 2)); kv.close(); diff --git a/utils/db.ts b/utils/db.ts index 17ed47e97..1adf32ee0 100644 --- a/utils/db.ts +++ b/utils/db.ts @@ -28,9 +28,7 @@ export const kv = await Deno.openKv(path); * ``` */ export async function collectValues(iter: Deno.KvListIterator) { - const values = []; - for await (const { value } of iter) values.push(value); - return values; + return await Array.fromAsync(iter, ({ value }) => value); } // Item diff --git a/utils/posts.ts b/utils/posts.ts index 2d04c820d..c44052b5f 100644 --- a/utils/posts.ts +++ b/utils/posts.ts @@ -68,13 +68,11 @@ export async function getPost(slug: string): Promise { * ``` */ export async function getPosts(): Promise { - const files = Deno.readDir("./posts"); - const promises = []; - for await (const file of files) { - const slug = file.name.replace(".md", ""); - promises.push(getPost(slug)); - } - const posts = await Promise.all(promises) as Post[]; - posts.sort((a, b) => b.publishedAt.getTime() - a.publishedAt.getTime()); - return posts; + const posts = await Array.fromAsync( + Deno.readDir("./posts"), + async (file) => await getPost(file.name.replace(".md", "")), + ) as Post[]; + return posts.toSorted((a, b) => + b.publishedAt.getTime() - a.publishedAt.getTime() + ); }