Your code runs asynchronously. The
forEach
method returns
before any of the
setTimeout
callbacks have executed, so none of your array items have been modified.
You already know that you need to use a Promise to wait for the callbacks to complete:
Using Promises - JavaScript | MDN[
^]
You need to turn the
setTimeout
call into a Promise:
javascript - How to make a promise from setTimeout - Stack Overflow[
^]
const later = (delay) => new Promise(resolve => setTimeout(resolve, delay));
You'll need to build up a list of promises, then wait for them all to complete:
Promise.all() - JavaScript | MDN[
^]
Array.prototype.map() - JavaScript | MDN[
^]
It's probably easiest to use
async
and
await
:
async function - JavaScript | MDN[
^]
Unfortunately, you can't use
await
in a top-level script, so you'll need to have an outer function to use it:
(async function(){
const promises = works.map(async (item) => {
await later(3000);
if (item.name === "CCF") {
item.workStatus.isComplete = true;
}
});
await Promise.all(promises);
console.log(works);
})();
Demo[
^]
If you want to stick to using callbacks:
const promises = works.map((item) => later(3000).then(() => {
if (item.name === "CCF") {
item.workStatus.isComplete = true;
}
}));
Promise.all(promises).then(() => console.log(works));
Demo[
^]