Skip to content

Instantly share code, notes, and snippets.

@frank-dspeed
Last active October 28, 2022 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frank-dspeed/308145947f5ff26bd2613f09b6b5f529 to your computer and use it in GitHub Desktop.
Save frank-dspeed/308145947f5ff26bd2613f09b6b5f529 to your computer and use it in GitHub Desktop.
CanJS Translation
{{# if(this.promise.isPending) }}
  Loading…
{{/ if }}
{{# if(this.promise.isRejected) }}
  Error: {{ this.promise.reason }}
{{/ if }}
{{# if(this.promise.isResolved) }}
  Result: {{ this.promise.value }}
{{/ if }}
const target = new HTMLElement();

target.innerHTML = `Loading…`;
fetch('').then(r=>r.body).then((val) => `Result: ${val}`, (reason) => `Error: ${reason}`)
  .then(html => { target.innerHTML = html; });

const html = ({ val, reason }={}) => `${(!val && !reason) 
    ? `Loading…` : val 
    ? `Result: ${val}` 
    : `Error: ${reason}`}`

const el = async (htmlTemplate, promise) => {
    const target = new HTMLElement();
    const updateTarget = (template) => target.innerHTML = template;
    
    promise.then((val) => ({ val }), (reason) => ({ reason }))
      .then(htmlTemplate).then(updateTarget);
    updateTarget(await htmlTemplate());
    
    return target;
}

// Custom Element that shows promise result or loading
el(html, fetch('').then(r=>r.body));
// Advanced info
// html() // => `Loading...`
// html({ val: "hi"}) // => `Result: hi`
// html({ reason: "bad"}) // => `Error: bad`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment