executed in order of waitTimes = [600, 400, 200]
.
Last active
April 23, 2022 19:51
-
-
Save kkdd/3371e97cd5f4b82ac5c18384d071e511 to your computer and use it in GitHub Desktop.
await asynchronous functions
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset=utf-8> | |
</head> | |
<body> | |
<div id='debug' style='padding:4px;background-color:#fffc;position:absolute;left:0;top:0;color:#0af;font-family:courier;font-size:12px;user-select:none'></div> | |
</body> | |
<script> | |
const strArrayDebug = []; | |
const waitTimes = [600, 400, 200]; | |
showDebugPush(`waitTimes = ${waitTimes}`); | |
(async () => { | |
showDebugPush("[using await for each]"); | |
for (const waitTime of waitTimes) { | |
await funcWait(waitTime); | |
showDebugPush(`waited for ${waitTime}ms. (in a for-loop)`); | |
} | |
showDebugPush("\n[using Promise.all]"); | |
const promise_all = await Promise.all(waitTimes.map(funcWait)); | |
showDebugPush(`result = ${promise_all}`); | |
showDebugPush(promise_all.toString() == waitTimes.toString()); | |
})(); | |
function funcWait(waitTime) { | |
const func_wait = (resolve) => { | |
setTimeout(() => { | |
resolve(waitTime); | |
showDebugPush(`waited for ${waitTime}ms.`); | |
}, waitTime); | |
}; | |
return new Promise(func_wait); | |
} | |
function showDebugPush(str) { | |
strArrayDebug.push(str); | |
document.getElementById("debug").innerText = strArrayDebug.join("\n"); | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment