async/await playing

by María Fernández

JavaScript

/*
Provide me with some code for making my favorite soup.
- To make soup you need a recipe, a chef, and a soup pan.
- The above code is a loose interface for a few methods which should get you what you need to make the soup

async function getSoupRecipe(<soupType>)
async function hireSoupChef(<soupRecipe:requiredSkills>)
async function buySoupPan()
async function makeSoup(<soupChef>, <soupRecipe>, <soupPan>)
*/

async function getSoupRecipe(soupType) {
  const soupRecipe = { requiredSkills: 'required-skills' };
	return new Promise(resolve => setTimeout(() => resolve(soupRecipe), 2000));
}

async function hireSoupChef(soupRecipe) {
	if (!soupRecipe || !soupRecipe.requiredSkills) {
  	return Promise.reject('error-hireSoupChef');
  }
  const soupChef = 'soup-chef';
	return new Promise(resolve => setTimeout(() => resolve(soupChef), 2000));
}

async function buySoupPan() {
  const soupPan = 'soup-pan';
	return new Promise(resolve => setTimeout(() => resolve(soupPan), 4000));
}

async function makeSoup(soupChef, soupRecipe, soupPan) {
  if (!soupChef || !soupRecipe || !soupPan) {
  	return Promise.reject('error-makeSoup');
  }
	return new Promise(resolve => setTimeout(() => resolve('Soup made !!!'), 2000));
}

async function giveMeMySoupVerySlow(soupType) {
	const start = performance.now();

	const recipe = await getSoupRecipe(soupType);
  const chef = await hireSoupChef(recipe);
  const pan = await buySoupPan();
  
  const soup = await makeSoup(chef, recipe, pan);

	const end = performance.now();
	const totalTime = end - start;
	console.log(`>>>>> mySoup: ${soup} took ${totalTime} ms.`)
}

async function giveMeMySoupSlow(soupType) {
	const start = performance.now();

	const recipePromise = getSoupRecipe(soupType);
  const panPromise = buySoupPan();
  
  const pan = await panPromise;
  const recipe = await recipePromise;
  const chef = await hireSoupChef(recipe)
  
  const soup = await makeSoup(chef, recipe, pan);

	const end = performance.now();
	const totalTime = end...