Skip to content

Instantly share code, notes, and snippets.

@FND
Created September 16, 2019 04:47
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 FND/15ace3f46964fc24025a37e578a43bfb to your computer and use it in GitHub Desktop.
Save FND/15ace3f46964fc24025a37e578a43bfb to your computer and use it in GitHub Desktop.
complate promises
// render view
let tree = frontpage({
title: "My Site",
groups: ["AAA", "BBB"]
});
console.log("ready to render", tree);
// views
function frontpage({ title, groups }) {
return createElement(Document, { title },
groups.map(id => (
createElement(List, { id })
)));
}
// macros
function Document({ title }, ...children) {
return createElement("body", {},
createElement("h1", {}, title),
...children);
}
function List({ id }) {
console.log(`retrieving group \`${id}\``);
return networkRequest().
then(() => createElement("ol", {},
[1, 2].map(i => (
createElement(Item, { context: id, id: i })
))));
}
function Item({ id, context }, ...children) {
let caption = `${context}:${id}`;
console.log(`retrieving item \`${caption}\``);
return networkRequest().
then(() => createElement("li", {}, caption));
}
// util
function createElement(tag, params, ...children) {
if(tag.call) { // macro
return tag(params, ...children);
}
console.log(`creating <${tag}>`, children);
return { tag, children };
}
// simulates asynchronous operation
function networkRequest(delay = randomInt(100, 500)) {
return new Promise(resolve => {
setTimeout(() => { resolve(); }, delay);
});
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment