Skip to content

Instantly share code, notes, and snippets.

@benqus
Last active June 13, 2024 06:35
Show Gist options
  • Save benqus/82ff5bc8bcb9f66e11aaff61b5864476 to your computer and use it in GitHub Desktop.
Save benqus/82ff5bc8bcb9f66e11aaff61b5864476 to your computer and use it in GitHub Desktop.

Revisions

  1. benqus revised this gist Jun 13, 2024. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions ssr.ts
    Original file line number Diff line number Diff line change
    @@ -9,6 +9,8 @@ async function render(...args: Array<any>) {
    }).join('');
    }

    const variable = 5;

    const result = await render`
    <!DOCTYPE html>
    <html lang="en">
    @@ -21,6 +23,7 @@ const result = await render`
    <script type="module" src="index.ts"></script>
    <h1>${async () => new Promise(res => setTimeout(() => res('Hello World!'), 1000))}</h1>
    <h2>${async () => new Promise((_, rej) => setTimeout(() => rej('error'), 1500))}</h2>
    <h3>${variable}</h3>
    </body>
    </html>
    `;
  2. benqus created this gist Jun 13, 2024.
    28 changes: 28 additions & 0 deletions ssr.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    async function render(...args: Array<any>) {
    const strings = args[0];
    const params = args.slice(1);
    const results = await Promise.allSettled(params.map(param => typeof param === 'function' ? param() : param));
    return strings.map((str: string, i: number): string => {
    const result = results[i];
    if (result == null) return str;
    return str + (result.status === 'fulfilled' ? result.value : result.reason);
    }).join('');
    }

    const result = await render`
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${() => 'Title'}</title>
    </head>
    <body>
    <script type="module" src="index.ts"></script>
    <h1>${async () => new Promise(res => setTimeout(() => res('Hello World!'), 1000))}</h1>
    <h2>${async () => new Promise((_, rej) => setTimeout(() => rej('error'), 1500))}</h2>
    </body>
    </html>
    `;

    console.log(result);