Recreating axios with ES6 promises

We have already used axios in this medium post and here is some code to refresh your memory.

axios.get(url)
.then(response => {
})
.catch(error => {
})

In this post, we will use promises to recreate the axios library. Of course, we are not going to implement everything that axios has, but we will try to do as much as we can in just 1 medium post. We will keep things simple and complex at the same time!

However, if you want me to make a full video course on recreating axios, then just leave a comment below.

Before we begin, let me tell you that this post is for developers who know JavaScript, asynchronous programming in JavaScript, have used axios, but they never had the chance to create promises on their own in ES6.

What are promises?

First, let’s create an index.html file with a script.

Now let’s create a class, I will call it Devlob, because I want to plug my company name (wink) (wink). Inside that class create a get function that accepts a url.

You should have this result:

<script>
class Devlob {
   get (url) {
   }
}
</script>

Now, what is a promise?

A promise is an object that will contain the result of an asynchronous operation. The operation may succeed or fail.

In the above screenshot you can see that it uses a callback which accepts two parameters, resolve and reject. Resolve means that the operation was successful and reject that it failed!

Thus, let’s create a promise in order to continue:

<script>
class Devlob {
   get (url) {
      let promise = new Promise((resolve, reject) => {
      })
   }
}
</script>

Fetching the response

Great, now inside the {}, we are going to add some code to fetch some api results.

For this purpose, we are going to use fetch, which is an updated method of XMLHttpRequest.

<script>
class Devlob {
   get (url) {
      let promise = new Promise((resolve, reject) => {
         fetch(url)
         .then(response => {
            resolve(response.json().then(data => (
               data.results
            )))
         })
         .catch(response => {
            reject("Api call failed!")
         })
      })
   }
}
</script>

As you can see, fetch accepts a string, which will be the url. Then fetch makes use of promises as well.

Thus, now we have then and catch. If the api call was successful, we go inside then and execute whatever is inside there. On the other hand, if the api call, was not successful, we go inside catch and again execute whatever is inside there.

We said that resolve is used for when the asynchronous operation is successful and since we are inside then, we want of course to use resolve there and reject inside catch.

Inside catch, we simply reject it with a message. Inside try, we resolve it by converting the response to json and get the results array of the response.

We are going to use this url as our api https://randomuser.me/api/?results=5 and as you can see the response has a results array.

However, we are not done yet, we need to include then/catch for our promise as well. For now, we can simply log the response that we get from fetch.

Because, remember that if fetch is successful, then it will resolve the promise, if it is not successful it will reject it, thus we go back to try/catch.

Alright, the updated code is this one:

<script>
class Devlob {
   get (url) {
      let promise = new Promise((resolve, reject) => {
         fetch(url)
            .then(response => {
               resolve(response.json().then(data => (
                  data.results
               )))
            })
           .catch(response => {
              reject(“Api call failed!”)
           })
         })
        .then(response => {
           console.log(response)
        })
        .catch(response => {
           console.log('error: ' + response)
        })
    }
}
</script>

Using the Devlob class

Now all we have to do is to use that get function inside the Devlob class.

Add this code after your class declaration:

let devlob = new Devlob()
devlob.get(“https://randomuser.me/api/?results=5")

If everything went well, then you should get the following result:

However, suppose you change the api url to this one https://thiswillfail.me/api/?results=5, then we get the message inside reject as seen below.

To conclude

Alright, this was just an introduction to promises, I will cover this topic more in the upcoming videos on the Devlob YouTube channel.

Hopefully, now you know what promises are and how axios works!

Like what you read? Give Devlob a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.