JavaScript promises enable developers to write asynchronous applications in JavaScript Loops are ways of iterating elements For instance doing an asynchronous task within a for loop can be done as follows; Note that lag is used to emulate some delay. const items = [1, 2, 3, 4] const lag = async (delay) => { return new Promise((resolve) => setTimeout(() => res(`${delay / 1000} sec`), delay)) } items.forEach(async (item) => { const seconds = await lag(1000 * item) console.log(seconds) }) expected output 1 sec 2 sec 3 sec 4 sec After running the code above every second some text was printed
Comments
Post a Comment