1.0.1 • Published 10 months ago

@enzoaicardi/pendingliteral v1.0.1

Weekly downloads
-
License
GPL-3.0-only
Repository
github
Last release
10 months ago

pendingliteral.js

A ridiculously small layer for using promises in template literals

NPM Version NPM Downloads Bundle Size JSDelivr Hits Wiki

List of all exports

  • pendingLiteral
  • pendingMerge

Usage

pendingLiteral can be useful when you need to wait for one or more promises to be resolved before building a string with template literals.

import { pendingLiteral as html } from "pendingliteral";

class MyCustomElement extends HTMLElement {
    constructor() {
        super();
    }
    connectedCallback() {
        // request a post from jsonplaceholder API
        const post = fetch("https://jsonplaceholder.typicode.com/posts/1").then(
            (response) => response.json()
        );
        // create the pendingLiteral
        const content = html`<div>Post: ${post.then((p) => p.title)}</div>`;
        // update the component's content
        content.then((html) => (this.innerHTML = content));
    }
}

pendingMerge can be useful if you need to attach a table that can contain promises in a pendingLiteral for example.

import { pendingLiteral, pendingMerge as merge } from "pendingliteral";

const string = pendingLiteral`
    some promises resolved:
    ${merge(
        [
            Promise.resolve().then(() => "[first promise]"),
            Promise.resolve().then(() => "[second promise]"),
            Promise.resolve().then(() => "[third promise]"),
        ],
        " - " /* second argument is optional */
    )}
`;

string.then((str) => console.log(str));

Installations

The pendingliteral layer is available as ESModule / IIFE / Commonjs.

NPM Package

npm install @enzoaicardi/pendingliteral
import { pendingLiteral, pendingMerge } from "@enzoaicardi/pendingliteral"; // es modules
const { pendingLiteral, pendingMerge } = require("@enzoaicardi/pendingliteral"); // commonjs modules

CDN import

// es modules
import {
    pendingLiteral,
    pendingMerge,
} from "https://cdn.jsdelivr.net/npm/@enzoaicardi/pendingliteral@latest/esm/pendingliteral.js";
<!-- iife function execution -->
<script src="https://cdn.jsdelivr.net/npm/@enzoaicardi/pendingliteral@latest/iife/pendingliteral.js"></script>
<script>
    // global object destructuration
    const { pendingLiteral, pendingMerge } = pendingliteral;
</script>