From 04b359678ba94656c2faaa79f818f66d0b070b8a Mon Sep 17 00:00:00 2001 From: KATT Date: Mon, 2 Oct 2023 22:28:56 +0200 Subject: [PATCH] cool --- .rfcs/001-serialize-async.md | 51 ++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/.rfcs/001-serialize-async.md b/.rfcs/001-serialize-async.md index 7e7513c2..9632b668 100644 --- a/.rfcs/001-serialize-async.md +++ b/.rfcs/001-serialize-async.md @@ -66,38 +66,43 @@ function asyncSerializer(value) { return [head, iterator]; } -export async function* asyncStringify(value) { - // first line of the json: init the array, ignored when parsing> - yield "[\n"; +export function asyncStringify(value) { + // head looks like - const [head, iterator] = asyncSerializer(value); + // [ + // {} + // ,[ - // (head is only called once) + const [head, iterator] = asyncSerializer(value); + // first line of the json: init the array, ignored when parsing> + let headAsString = "[" + "\n"; // second line: the shape of the json - used when parsing> - yield JSON.stringify(head) + "\n"; + headAsString += JSON.stringify(head) + "\n"; // third line: comma before values, ignored when parsing - yield ","; - yield "["; // values start - yield "\n"; - let isFirstStreamedValue = true; - - for await (const chunk of iterator) { - if (!isFirstStreamedValue) { - // add a comma between each value to ensure it's valid JSON - // needs to be ignored - yield ","; + headAsString += ",[" + "\n"; + + async function* serializedAsString() { + let isFirstStreamedValue = true; + for await (const chunk of iterator) { + if (!isFirstStreamedValue) { + // add a comma between each value to ensure it's valid JSON + // will be ignored when parsing ignored + yield ","; + } + + isFirstStreamedValue = false; + yield JSON.stringify(chunk.value) + "\n"; + + yield "\n"; + continue; } - isFirstStreamedValue = false; - yield JSON.stringify(chunk.value) + "\n"; - - yield "\n"; - continue; + yield "]"; // end value array + yield "]"; // end response } - yield "]"; // end value array - yield "]"; // end response + return [headAsString, serializedAsString()]; } ```