Created
September 16, 2019 04:47
-
-
Save FND/15ace3f46964fc24025a37e578a43bfb to your computer and use it in GitHub Desktop.
complate promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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