Skip to content

Instantly share code, notes, and snippets.

@Zydnar
Last active February 13, 2022 21:51
Show Gist options
  • Save Zydnar/59bc516d52b43a690466fec405b9e7cd to your computer and use it in GitHub Desktop.
Save Zydnar/59bc516d52b43a690466fec405b9e7cd to your computer and use it in GitHub Desktop.
Asynchronously append children keeping their order
/** Sleep function for testing purposes **/
export const sleep = (t: number) => new Promise(r=> setTimeout(r, t));
/** Asynchronously append children keeping their order **/
export async function asyncAppendInOrder(arr: Promise<Element>[], parent: Element): Promise<Element> {
const div = document.createElement("div");
const textNode = document.createTextNode('Loading...');
div.append(textNode);
arr
.map(async (element) => {
/* true to keep text content alternatively you could change div styling to indicate loading */
const clone = div.cloneNode(true);
parent.append(clone);
element
/* replace placeholder when child will be ready. */
.then(el => parent.replaceChild(el, clone));
});
return parent;
}
//testing
const $0 = document.getElementById('foo');
asyncAppendInOrder([
(async()=>{await sleep(1000); const div = document.createElement('div'); div.innerHTML = '1'; return div})(),
(async()=>{await sleep(5000); const div = document.createElement('div'); div.innerHTML = '2'; return div})(),
(async()=>{await sleep(100); const div = document.createElement('div'); div.innerHTML = '3'; return div})(),
(async()=>{await sleep(8000); const div = document.createElement('div'); div.innerHTML = '4'; return div})(),
(async()=>{await sleep(10000); const div = document.createElement('div'); div.innerHTML = '5'; return div})(),
(async()=>{await sleep(200); const div = document.createElement('div'); div.innerHTML = '6'; return div})(),
], $0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment