Skip to content

Instantly share code, notes, and snippets.

@Goloburda
Created March 2, 2020 09:18
Show Gist options
  • Select an option

  • Save Goloburda/b34bda997d14d7e942d1ec24c529e71d to your computer and use it in GitHub Desktop.

Select an option

Save Goloburda/b34bda997d14d7e942d1ec24c529e71d to your computer and use it in GitHub Desktop.

Revisions

  1. Goloburda created this gist Mar 2, 2020.
    37 changes: 37 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    const cache = new Map();

    const setCallback = (element, key) => {
    if (cache.has(key)) {
    return cache.get(key);
    }

    throw element;
    };

    const asyncElement = new Promise(res => {
    setTimeout(() => {
    res("Mikita");
    }, 1000);
    });

    const render = () => {
    const root = document.querySelector("#app");
    if (root.firstChild) {
    root.firstChild.remove();
    }
    const element = document.createElement("div");
    let text = "loading...";
    try {
    text = setCallback(asyncElement, "name");
    } catch (promise) {
    promise.then(data => {
    cache.set("name", data);
    render()
    });
    }

    element.textContent = text;
    root.appendChild(element);
    };

    render();