Last active
February 13, 2022 21:51
-
-
Save Zydnar/59bc516d52b43a690466fec405b9e7cd to your computer and use it in GitHub Desktop.
Asynchronously append children keeping their order
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
/** 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