Created
June 10, 2020 15:03
-
-
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
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 () { | |
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