Categories
Object-Oriented JavaScript

Object-Oriented JavaScript — Promises

Spread the love

JavaScript is partly an object-oriented language.

To learn JavaScript, we got to learn the object-oriented parts of JavaScript.

In this article, we’ll look at JavaScript promises.

Promises

A promise is an alternative to callbacks.

Promises let us retrieve the results of an async function calls.

Promises are easier than callbacks and gives us more readable code.

They can take on a few states.

A promise can be pending, which means the result isn’t ready yet.

This is the initial state.

A promise is fulfilled when the result is ready.

If there’s an error, then the result is rejected.

When a pending promise is fulfilled or rejected, associated callbacks that are queued up by then are run.

This is better than async callbacks.

If we have many async functions we want to run, then we’ll have to nest them repeatedly.

For instance, we write:

asyncFunction(arg, result => {
  asyncFunction(arg, result => {
    //...
  })
})

to run an async function more than once.

If we have to do that more, then there’s more nesting and it’ll be harder to read.

If asyncFunction is a promise, then we can just call then with a callback.

And the callback run with the promise is fulfilled:

asyncFunction(arg)
  .then(result => {
    //...
  });

We just keep calling then until we called all the promises we want:

asyncFunction(arg)
  .then(result => {
    //...
    return asyncFunction(argB);
  })
  .then(result => {
    //...
  })

The then callback returns a promise, so we can keep calling then until we’re done.

To catch promise errors, we can call the catch method with a callback.

For instance, we can write:

readFileWithPromises('text.json')
  .then(text => {
    //...
  })
  .catch(error => {
    console.error(error)
  })

Creating Promises

We can create promises with the Promise constructor.

For instance, we can write:

const p = new Promise(
  (resolve, reject) => {
    if (...) {
      resolve(value);
    } else {
      reject(reason);
    }
  });

We passed in a callback that has the resolve and reject parameters, which are all functions.

resolve fulfilled the promise with a given value.

reject rejects a promise with a value.

We can use than with then and catch as we did with the previous examples:

p
  .then(result => {
    //...
  })
  .catch(error => {
    //...
  })

When we throw an error in the then callback, it’ll also be caught with catch if it’s called after the then that throws the error:

readFilePromise('file.txt')
  .then(() => {
    throw new Error()
  })
  .catch(error => {
    'Something went wrong'
  });

Promise.all()

Promise.all lets us run an array of promises in parallel and returns a promise that resolves to an array of all the promises in the array.

If all of them are fulfilled, then an array of the results of the promises will be returned in then then callback’s parameter.

For instance, we can write:

Promise.all([
    p1(),
    p2()
  ])
  .then(([r1, r2]) => {
    //
  })
  .catch(err => {
    console.log(err)
    ''
  })

We call Promise with p1 and p2 which return promises.

Then r1 and r2 are the results.

catch catches error from any of the promises if any of them are rejected.

Conclusion

We can create promises with the Promise constructor.

Promise.all run multipole promises in parallel and returns a promise that resolves to an array of all the results,.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *