Last active
February 15, 2022 20:15
-
-
Save webuniverseio/12a8d81650e34c645789dc6fc383fbc6 to your computer and use it in GitHub Desktop.
exercise of fetching in random order, but rendering in logical order
This file contains hidden or 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
function fetchAndLog(urls) { | |
const pending = new Map() | |
let lastProcessed = -1 | |
urls.map((x, i) => { | |
return fetch(x).then(x => { | |
if (lastProcessed === i - 1) { | |
console.log(x.json()) | |
checkPending(++lastProcessed) | |
} else { | |
pending.set(i, x.json()) | |
} | |
}); | |
}) | |
function checkPending(i) { | |
if(pending.has(++i)) { | |
console.log(pending.get(i)) | |
checkPending(++lastProcessed) | |
} | |
} | |
} | |
function fetch(url) { | |
return wait().then(() => ({ | |
json: () => ({id: url.match(/id=(\d+)/)[1]}) | |
})) | |
} | |
let x = 0 | |
const v = [156, 111, 2700, 135] | |
function wait() { | |
return new Promise(resolve => setTimeout(resolve, v[x++] /*random(100, 300)*/)) | |
} | |
function random(min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min | |
} | |
fetchAndLog([ | |
'https://httpbin.org/get?id=1', | |
'https://httpbin.org/get?id=2', | |
'https://httpbin.org/get?id=3', | |
'https://httpbin.org/get?id=4' | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment