Created
August 12, 2022 14:41
-
-
Save iOnline247/834be4c6e1fa9ea0677739379c38bbae to your computer and use it in GitHub Desktop.
`for await` examples
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
async function* iteratorGen(arr) { | |
for (const i of arr) { | |
if (typeof i === "function") { | |
yield i(); | |
} else { | |
yield i; | |
} | |
} | |
} | |
function delay(ms, value, pass = true) { | |
return new Promise(function (res, rej) { | |
setTimeout((v) => (pass ? res(v) : rej(v)), ms, value); | |
}); | |
} | |
async function main() { | |
console.time("concurrently"); | |
const iterator = iteratorGen([ | |
delay(10000, 0), | |
delay(200, 1), | |
delay(1000, 2), | |
delay(12000, 3), | |
]); | |
const values = []; | |
for await (let x of iterator) { | |
console.group(x); | |
console.log(`timestamp: ${Date.now()}`); | |
console.log(`value: ${x}`); | |
console.log(`previous value: ${values[x - 1]}`); | |
console.groupEnd(x); | |
values.push(x); | |
} | |
console.timeEnd("concurrently"); | |
} | |
main() | |
.then((r) => console.log(r)) | |
.catch((err) => console.log(err)); | |
// concurrently: 12012ms - timer ended |
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
async function* iteratorGen(arr) { | |
for (const i of arr) { | |
if (typeof i === "function") { | |
yield i(); | |
} else { | |
yield i; | |
} | |
} | |
} | |
function delay(ms, value, pass = true) { | |
return new Promise(function (res, rej) { | |
setTimeout((v) => (pass ? res(v) : rej(v)), ms, value); | |
}); | |
} | |
async function main() { | |
console.time("waterfall"); | |
const iterator = iteratorGen([ | |
delay.bind(null, 10000, 0), | |
delay.bind(null, 200, 1), | |
delay.bind(null, 1000, 2), | |
// delay.bind(null, 1000, new Error('yo'), false), | |
delay.bind(null, 12000, 3), | |
]); | |
const values = []; | |
for await (let x of iterator) { | |
console.group(x); | |
console.log(`timestamp: ${Date.now()}`); | |
console.log(`value: ${x}`); | |
console.log(`previous value: ${values[x - 1]}`); | |
console.groupEnd(x); | |
values.push(x); | |
} | |
console.timeEnd("waterfall"); | |
} | |
main() | |
.then((r) => console.log(r)) | |
.catch((err) => console.log(err)); | |
// waterfall: 24032ms - timer ended |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment