How to use async/await with forEach loop in JavaScript?

Asynchronous gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code.

Async/await is used to write asynchronous code. 

Approach

  • Create an array eg. myArray that contains some values.
  • Create an async main function that calls another async function that says doSomethingAsync
  • Now create an async function in which we use setTimeout to print all the items of the array.
  • This function returns a promise that resolves when the delay is complete.
<script>
	const myArray = [1, 2, 3, 4, 5];
    
	// A function that returns a promise
	// that resolves after a random delay
	async function doSomethingAsync(item) {
		return new Promise(resolve => {
			setTimeout(() => {
				console.log(item);
				resolve();
			}, Math.random() * 1000);
		});
	}

	async function main() {

		// Wait for all promises returned by
		//doSomethingAsync to resolve.
		await Promise.all(
		
			// Use map to create an array of promises,
			// with one promise for each item in myArray.
			myArray.map(async item => {
				
				// Wait for the promise returned by
				//doSomethingAsync to resolve.
				await doSomethingAsync(item);
			})
		);
	}

	// Call main to start the program.
	main();
</script>

Try it

Explanation

  • The main function is marked as async, which means it returns a promise.
  • We use Promise.all to wait for all the promises returned by doSomethingAsync to complete before moving on to the next line of code.
  • Inside the Promise.all calls, we use a map to create an array of promises that each call doSomethingAsync for a single item in the array.
  • We use the await keyword to wait for each promise to complete before moving on to the next item in the array.

Another Example 

<script>
	const myArray = ["brighten", "minds", "code"];

	// A function that returns a promise
	//that resolves after a random delay
	async function doSomethingAsync(item) {
		return new Promise(resolve => {
			setTimeout(() => {
				console.log(item);
				resolve();
			}, Math.random() * 1000);
		});
	}

	async function main() {

		// Wait for all promises returned
		// by doSomethingAsync to resolve
		await Promise.all(

			// Use map to create an array of promises,
			// with one promise for each item in myArray
			myArray.map(async item => {
				
				// Wait for the promise returned by
				// doSomethingAsync to resolve
				await doSomethingAsync(item);
			})
		);
	}

	// Call main to start the program.
	main();
</script>

Try it

Explanation

Due to the delay in printing elements, another element ” for ” is printed before the first element “geeks” in myArray to save time. It depicts that the asynchronous function run simultaneously.