DEV Community

loading...

Retrieving Data from Promise: then() & catch()

Swarnali Roy
I am a Junior Software Engineer. Learning new things and sharing those with fellow developers.
・Updated on ・2 min read

Hello Dear Readers & Fellow Developers!

In the previous post, I have shown the way to create a Promise which is a very important concept to know.
[ https://dev.to/swarnaliroy94/javascript-concept-of-promise-3ijb ]

The pending state starts immediately after generating a Promise and holds until it is either resolved or rejected.
Having said that, while working with React.JS or React Native, we can set the initial state as pending state, set resolve in the then section and set reject in catch section.

Here comes a question, what is this then & catch section?

In JavaScript, we often struggle to deal with asynchronous operations . There comes the concept of Promise, with which we can deal with those operations. To understand how to retrieve data from a Promise, the then & catch concept is very important.

A completely off topic is, I struggled a lot to understand how a Promise actually works. It has been 8 months now and from the experience that I gathered , I will try to make this post as simple as I can.

Let's get started with understanding How to Retrieve Data from Promise.

First of all, let's create a promise for example.

const addition = (a, b) =>
  new Promise((resolve, reject) => {
    if (typeof a == "number" && typeof b == "number") {
      resolve(a + b);
    } else {
        reject ("Not a Number")
    }
  });
Enter fullscreen mode Exit fullscreen mode

The example shows a function called addition, which is a Promise that takes two parameters, a & b. The if code block holds a condition that checks if both a & b are numbers with the typeof operator.
[ https://dev.to/swarnaliroy94/javascript-data-types-and-debugging-type-errors-with-typeof-3mao ].

Resolve

When we execute the Promise that we created in the above example, if it is resolved, the then block is executed and we can get the result from the callback function . In this example, this Promise will be resolved and return the summation of a & b, if and only if both a & b are numbers. The example is given below.

addition(10, 5)
  .then((response) => {
    console.log(response);
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode

The output of this example will show the summation 15 as both 10 & 5 are numbers.

Reject

The Promise will be rejected if any of the values of a or b is not a number & will be captured in the catch block.

addition(10, "5") 
  .then((response) => {
    console.log(response);
  })
  .catch((err) => {
    console.log(err);
  });
Enter fullscreen mode Exit fullscreen mode

The output of this example shows the message "Not a Number", as 10 is a number but "5" is a string, which doesn't fulfill the condition of the Promise.

Basically, then is capturing the success state & catch is capturing the error/failure state.

There are other ways of executing the same concept. We can use Async/Await to make it more compact. I will write about it in the next post. I hope, I was able to make it simple and understandable. But if there is any confusion, questions are always welcomed in the discussion section.

Discussion (8)

Collapse
jakakosir profile image
jakakosir

πŸ‘

Collapse
swarnaliroy94 profile image
Swarnali Roy Author

😌

Collapse
imtridevsharma profile image
im-tridevsharma

Right πŸ‘

Collapse
swarnaliroy94 profile image
Swarnali Roy Author

Thanks 😊

Collapse
askindzer profile image
Andrei Skindzer • Edited

Is there a way to save data in another variable, not a Promise but resolved value?
Ex:
const addition = (a, b) =>
new Promise((resolve, reject) => {
if (typeof a == "number" && typeof b == "number") {
resolve(a + b);
} else {
reject ("Not a Number")
}
});

let a;

addition(2,5).then((response)=>{
a=response
});

console.log(a);

// Output:
// underfined

Collapse
swarnaliroy94 profile image
Swarnali Roy Author • Edited

The example that you've given won't work as when you are assigning a, it's value is 'undefined' and the console.log(a) will be undefined at the time of execution because, it is delayed by the promise and pushed to the event queue.
If you want to access the changed value , you need to follow up with another then or do something that put your code in the event queue after the assignment.
Ex:

const addition = (a, b) =>
new Promise((resolve, reject) => {
if (typeof a == "number" && typeof b == "number") {
resolve(a + b);
} else {
reject ("Not a Number")
}
});

let a;

addition(2,5).
    then((response)=>{
            a=response
    }).then(()=>{
    console.log(a)
})
//console.log(a);
Enter fullscreen mode Exit fullscreen mode

or

addition(2,5).then((response)=>{
a=response
})
setTimeout(() => console.log(a), 0);
Enter fullscreen mode Exit fullscreen mode

Depending on your need, you can look at closures in JS to learn more.
Hope this works

Collapse
ali_ah profile image
Ali Ahmad

Thank you πŸ‘, although i know this concepts in JS but i read the 2 parts

Collapse
swarnaliroy94 profile image
Swarnali Roy Author

Thanks a lot. The next part will be uploaded today, hope you'll read that too.