JS 6

  • Promises

  • kinda

A Promise is an object, that resolves or rejects an asynchronous function and its value, it has the methods promise.then(), promise.catch() and promise.finally(), from Promise.prototype:

//resolve/reject arguments are the parameters in then(e) and catch(error)

const myPromise = new Promise(function (resolve, reject) {
  let sampleData = [2, 4, 6, 8];

  (sampleData[1]) ? resolve( "resolved string" ) : reject('An error occured!');
});

myPromise
  .then(function (e) {
    console.log(e);          //"resolved string"
  })
  .catch(function (error) {
    throw new Error(error);  //if reject we get Error('An error occured!')
  })
  .finally(function () {
    console.log('PROMISE COMPLETED');  //printed in any case
})

The .then() method can take 2 arguments, they are callback functions, for the Promise resolve and reject, while catch() has only one for handling errors:

Promise.all() takes an iterable of promises as input, and returns a promise:

Promise.all() needs all its promises to be resolved, it will wait until all promises are fulfilled:

We can use .catch() to check each single promise:

Api and Fetch()

Fetch() allows us to send network request and load information, without reloading the page, it returns a Promise:

At this stage we don't have a body yet, we check the HTTPS status for errors:

The response promise object provides methods to access it in various formats:

The response needs to await, for code that has yet to return we use async functions.

Response.body / response.json() / a specific property

We can use await on simple promises:

Promises can only change from pending to fulfilled or pending to rejected. They cannot change from fulfilled back to pending or rejected back to pending.

The Blob object can represent data as a file-like object that doesn't need to be in a javascript-native format, like images.

The response.blob() method's promise renders an image with URL.createObjectURL().

The response interface returns the header read-only property object:

The bind() method allows us to keep THIS argument when in a callback function:

The Request() object will go from the client to the server:

Some Promise() based exercises solutions

Last updated