JSFiddle - React, Tailwind, and code Playground
JavaScript
const array = [1, 2, 3];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
for (const itemOfArray of array) {
console.log(itemOfArray);
}
for (const itemInArray in array) {
console.log(itemInArray);
}
const brothers = {
id1: {name: "Sébastien", age: 34},
id2: {name: "Antoine", age: 23}
};
function incrementBrothersAges() {
return Object.entries(brothers)
.reduce((acc,[id,brother]) => {
acc[id] = {...brother,age: brother.age + 1};
return acc;
},{})
}
console.log("incrementBrothersAges",incrementBrothersAges())
async function runCountryTask(country) {
const taskDuration = Math.random() * 2000;
await new Promise(resolve => setTimeout(resolve, taskDuration))
console.log(`Task complete for ${country}, duration=${taskDuration}`)
}
async function forEachAsyncSequential(array,asyncFn) {
for (const item of array) {
await asyncFn(item);
}
}
async function forEachAsyncSequential2(array,asyncFn) {
await array.reduce((acc,item) => {
return acc.then(() => asyncFn(item))
},Promise.resolve());
}
async function runAllCountryTasks() {
const countries = ["FR","EN","US","DE","UK","IT"];
await Promise.all(countries.map(runCountryTask))
console.log("\n");
await forEachAsyncSequential(countries,runCountryTask);
console.log("\n");
await forEachAsyncSequential2(countries,runCountryTask);
console.log("\n");
}
runAllCountryTasks();