Skip to content

Instantly share code, notes, and snippets.

@kkdd
Last active April 23, 2022 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkdd/3371e97cd5f4b82ac5c18384d071e511 to your computer and use it in GitHub Desktop.
Save kkdd/3371e97cd5f4b82ac5c18384d071e511 to your computer and use it in GitHub Desktop.
await asynchronous functions

executed in order of waitTimes = [600, 400, 200].

<!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