Promises & Async Await - Vincentvanleeuwen/js-bootcamp GitHub Wiki

Promises

A promise is an object. A promise can be pending, fulfilled or rejected. You can use fetch() as the pending status, then() as the fulfilled status and catch() as the rejected status.

What you can see here is how a promise is set up. You start by creating a variable e.g. promise and assign the fetch method of the API. If you get the data without errors, it runs the .then() function, else it runs the .catch() function.

// Create a new promise
let promise = 
   // Method used to fetch a resource
   fetch(apiUrl);
promise.then(getData);
promise.catch(getError);
 
function getData(data) {
   console.log(data)
}
function getError(error) {
   console.log(error);
}

Time to refactor some of this code so it won't be as messy.

 fetch(apiUrl)
   .then(response => response.json())
   .then(json => console.log(json))
   .catch(err => console.log(err));

If you want to add a second Api to the promise, you can do it like this.

 fetch(apiUrl)
   // Because it's an arrow function you dont need to write return.
   .then(response => response.json())
   .then(json => {
      console.log(json);
      return fetch(secondApi + json);
   })
   .then(response => response.json())
   .then(json => {
     console.log(json.apiData);
   })
   .catch(err => console.error(err));

In the next example you can see how you create a new Promise.

function delayPromise(time) {
   return new Promise((resolve, reject) => {
     if(isNaN(time)) {
       reject(new Error("Delay requires a number");
     }
     
     setTimeout(resolve, time);
   }
}
delay('aaaa')
  .then(() => console.log("Hey"))
  .catch((error) => console.error(err));

You can also turn your promise into an asynchronous function

async function randomPromise() {
 let response1 = await fetch(randomApi);
 let json1 = await response1.json();
 let response2 = await fetch(somethingElse);
 let json2 = await response2.json();
 return {
   data: json1.data,
   data2: json2.data
 }
randomPromise()
  .then(results => results.data + results.data2)
  .catch(error => console.error(err);

Promise.all makes sure all the promises are returned in the correct order at the same time. The thing is that it's all or nothing.

let promises = [promise(1), promise(2), promise(3)];
Promise.all(promises)
  .then((result) => {
    for(let i = 0; i < result.length; i++){
       console.log(data);
       console.log(data2);
    }
  })
  .catch(err => console.error(err));