Skip to content

Instantly share code, notes, and snippets.

@1isten
Created June 10, 2020 15:03
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 1isten/e51cbae6e6b77222e41729eabbb8ed30 to your computer and use it in GitHub Desktop.
Save 1isten/e51cbae6e6b77222e41729eabbb8ed30 to your computer and use it in GitHub Desktop.
forEach does not support break or continue, each iteration involves a new callback
(async function () {
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// SyntaxError: Illegal break statement
arr.forEach(n => {
if (n === 3) {
break;
}
console.log(n);
});
// SyntaxError: Illegal continue statement: no surrounding iteration statement
arr.forEach(n => {
if (n === 3) {
continue;
}
console.log(n);
});
// for loop is ok with break
for (const n of arr) {
if (n === 3) {
break;
}
console.log(n);
}
// for loop is ok with continue
for (const n of arr) {
if (n === 3) {
continue;
}
console.log(n);
}
// while is ok with break
let i = 0;
while (i < arr.length) {
if (i === 3) {
break;
}
console.log(arr[i++]);
}
// while is ok with continue
let i = 0;
while (i < arr.length) {
if (i === 3) {
i++; // don't forget ++, otherwise the loop never ends
continue;
}
console.log(arr[i++]);
}
// do while is ok with break
let i = 0;
do {
if (i === 3) {
break;
}
console.log(arr[i++]);
} while (i < arr.length);
// do while is ok with continue
let i = 0;
do {
if (i === 3) {
i++; // don't forget ++, otherwise the loop never ends
continue;
}
console.log(arr[i++]);
} while (i < arr.length);
// involves 10 independent async callbacks, one callback will no await for another, so total delay is arround 1s
arr.forEach(async n => {
const m = await new Promise(resolve => setTimeout(() => resolve(n * 2), 1000));
console.log(m);
});
// involves only the outter async function, each iteration await for 1s
for (const n of arr) {
const m = await new Promise(resolve => setTimeout(() => resolve(n * 2), 1000));
console.log(m);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment