looping promises with async and await

by Anchit Gupta

JavaScript

//sample code

export async function chain(){
	let endpoint = "https://api.github.com/users",
		endpoint2 = "https://api.github.com/user/";
	let urls = [`${endpoint}/anchit05`, `${endpoint}/anchit05/repos`, `${endpoint}/anchit05/subscriptions`];
	let ids = [10526016, 1456904];

	// using method reduce, while reduce() doesn’t wait for any resolution to take place, 
	// the advantage it does provide is the ability to pass something back into the same callback after each run, 
	// a feature unique to reduce()

	function methodThatReturnsAPromise(id) {
	  return new Promise((resolve, reject) => {
	  	fetch(endpoint2 + id)
	  	.then(response => response.json())
      	.then(jsonResponse => {
      		console.log(`Resolve! ${new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getMinutes() + ":" + new Date().getMilliseconds()}`);
      		resolve();
      	})
      	.catch(ex => {
	        reject(ex);
	    });
	  });
	}

	ids.reduce((accumulatorPromise, nextID) => {
		console.log(`Loop! ${new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getMinutes() + ":" + new Date().getMilliseconds()}`);

		return accumulatorPromise.then(() => {
    		return methodThatReturnsAPromise(nextID);
  		});

	}, Promise.resolve());

	// With promise all, api call will happen parelley without any particular order and will resolve when all are done.

	// try{
	// 	let arrayOfPromises = urls.map(function(url, index) {
	// 		console.log("got data url: ", url);
	// 		return axios.get(url); // return raw promise
	// 	});
	// 	let [profile, repos, subs] = await Promise.all(arrayOfPromises);
	// 	console.log("all done");
	// 	console.log("profile: ", profile);
	// } catch(e){
	// 	console.log(e.message);
	// }

	// with for loop everthing will happen in sync

	// for ( let i=0; i< urls.length; i++ ){
	// 	let url = urls[i];

	// 	const data = await axios.get(url);

	// 	console.log("got data url: ", url);
	// }

	// With forEach, it will excetue the code...