1.2.0 • Published 12 months ago
@enzoaicardi/pendingliteral v1.2.0
pendingliteral.js
A ridiculously small layer for using promises in template literals
List of all exports
- pendingLiteral
 
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));
    }
}Derived usages
If you need to perform actions on arrays, such as join, reduce, etc... Just use Promise.all.
import { pendingLiteral } from "pendingliteral";
const string = pendingLiteral`
    some promises resolved:
    ${Promise.all([
        Promise.resolve().then(() => "[first promise]"),
        Promise.resolve().then(() => "[second promise]"),
        Promise.resolve().then(() => "[third promise]"),
    ]).then((values) => values.join(" - "))}
`;
string.then((str) => console.log(str));Installations
The pendingliteral layer is available as ESModule / IIFE / Commonjs.
NPM Package
npm install @enzoaicardi/pendingliteralimport { pendingLiteral } from "@enzoaicardi/pendingliteral"; // es modules
const { pendingLiteral } = require("@enzoaicardi/pendingliteral"); // commonjs modulesCDN import
// es modules
import { pendingLiteral } 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 } = pendingliteral;
</script>