You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constmyBirthday=(isSick)=>{returnnewPromise((resolve,reject)=>{setTimeout(()=>{if(!isSick){resolve(2);}else{reject(newError("I am sad"));}},2000);});};myBirthday(false).then((result)=>{console.log(`I have >{result} cakes`);// In the console: I have 2 cakes}).catch((error)=>{console.log(error);// Does not run}).finally(()=>{console.log("Party");// Shows in the console no matter what: Party});
Promise, Async, Await, Try, Catch (Build a guessing game)
constenterNumber=()=>{returnnewPromise((resolve,reject)=>{constuserNumber=Number(window.prompt("Enter a number (1 - 6):"));// Ask the user to enter a numberconstrandomNumber=Math.floor(Math.random()*6+1);// Pick a random number between 1 and 6// If the user enters a value that is not a number, run reject with an errorif(isNaN(userNumber)){reject(newError("Wrong Input Type"));}// If the user's number matches the random number, return 2 pointsif(userNumber===randomNumber){resolve({points: 2,
randomNumber,});// If the user's number is different than the random number by 1, return 1 point}elseif(userNumber===randomNumber-1||userNumber===randomNumber+1){resolve({points: 1,
randomNumber,});// Else return 0 points}else{resolve({points: 0,
randomNumber,});}});};constcontinueGame=()=>{returnnewPromise((resolve)=>{// Ask if the user want to continue the game with a confirm modalif(window.confirm("Do you want to continue?")){resolve(true);}else{resolve(false);}});};// option 2constcontinueGame=()=>{returnnewPromise((resolve)=>resolve(window.confirm("Do you want to continue?")));};consthandleGuess=async()=>{try{constresult=awaitenterNumber();// Instead of the then method, we can get the result directly by just putting await before the promisealert(`Dice: >{result.randomNumber}: you got >{result.points} points`);constisContinuing=awaitcontinueGame();if(isContinuing){handleGuess();}else{alert("Game ends");}}catch(error){// Instead of catch method, we can use the try, catch syntaxalert(error);}};handleGuess();// Run handleGuess function
Async, Await (Fetch country info from an API)
constfetchData=async()=>{// fetch() returns a promise, so we need to wait for itconstres=awaitfetch("https://restcountries.eu/rest/v2/alpha/col");// res is now only an HTTP response, so we need to call res.json()constcountry=awaitres.json();console.log(country);// Columbia's data will be logged to the dev console};fetchData();
Promise.all Async, Await (Fetch a country's neighboring countries)