Skip to content

Instantly share code, notes, and snippets.

@iOnline247
Created August 12, 2022 14:41
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 iOnline247/834be4c6e1fa9ea0677739379c38bbae to your computer and use it in GitHub Desktop.
Save iOnline247/834be4c6e1fa9ea0677739379c38bbae to your computer and use it in GitHub Desktop.
`for await` examples
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
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