Promises In JavaScript Made By Rocky

Promises In JavaScript Made By Rocky

A Promise was once made to fetch all the data about the gold from the KGF servers, let see how Rocky fulfills this promise.

·

3 min read

What is a Promise & It's Syntax

The Promise object represents an asynchronous operation's eventual completion (or failure) and its resulting value.

In our case, we had promised to fetch all the gold from the KGF server and display it, but at the time of the creation of the promise, We did not know whether it would happen.

rockyPromise = new Promise((resolve, reject) => {
  // The body of the promise, like the start of Rocky's journey
});

Here, the new Promise() statement from ES6 is used to construct a promise called rockyPromise. This promise is then formed and takes in a callback function with two arguments, resolve and reject, which are used to handle the success and failure of the API respectively.

So, How does a Promise Work?

In a real-world scenario, we may call multiple APIs within our code and we will not receive the response at that instant. It may take some seconds to receive and to simulate the same we are using the setTimeout function over here.

rockyPromise = new Promise((resolve, reject) => {
  let success = true; // Replace this with an actual condition or operation

  setTimeout(() => {
    if (success) {
      resolve("Rocky gets to the Gold");
    } else {
      reject("Rocky gets Nothing");
    }
  }, 2000); // Simulating an asynchronous operation like Rocky's challenges
});

Here we are also setting a variable success to trigger the error case(i.e. the case when the API fails)

Coming to code, the promises as mentioned have a callback function and have two arguments resolve and reject, if there isn't any error(if success) we call the resolve function, and if it falls the reject function respectively.

Here you can see that after the timeout of 2 seconds, if the promise was fulfilled Rocky gets gold as the success is set to true.

Handling Promises (resolve & then)

So far, we've spoken about the promise's formation; let's go on to discuss how to manage/handle promises' resolution and rejection.

As previously stated, in the event of a success, we resolve the promise. The resolve function is given by the promise object and is linked to the then function, which accepts a function as an input and applies it.

resolve("Rocky gets to the Gold") here the string that has been given to the resolve function as a parameter is received at the then function and gets stored in the variable result.

rockyPromise.then((result) => {
  console.log(result); // Output: "Rocky gets to the Gold"
});

Handling Failures (reject & catch)

Rocky may not get gold every time right, so in case he fails to do go(i.e. the API failed or got an error back) we use the reject function instead of the resolve and pass down a message.

Just like the message given in resolve got to the then the message which was given the reject part will be passed to the catch function and will be stored in the error parameter.

rockyPromise.catch((error) => {
  console.log(error); // Output: "Rocky gets Nothing"
});

Chaining Promises: What Happens Then?

So what happens after then, we could even chain multiple then statements and display them let's say the result return may also take some time to process in that case we can chain another statement and process it using that as well.

rockyPromise
  .then((result) => {
    console.log(result); // Output: "Rocky gets to the Gold"
    return "Rocky goes to the sea"; // New stage in the journey
  })
  .then((newResult) => {
    console.log(newResult); // Output: "Rocky goes to the sea"
  })
  .catch((error) => {
    console.log(error);  // Output: "Rocky gets Nothing"
  });

Conclusion: That is it, everyone!

I hope you all got to know about how Rocky handled that promise that he had once made to his mother using JavaScript. There are some videos and blogs that I used as references and you could refer to them as well to gain more in-depth knowledge about the same.

Reference Materials

Promises In JavaScript: https://youtu.be/NJwRQgsu1Q8

MDN Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise