Promise in React and React Native

Tejas Khartude
2 min readNov 14, 2023

--

A promise is an assurance that we will do something in the future, the same as real-life promises. These promises will either be kept when the time comes or they won’t. Similarly, this works in React Native too. When we make a promise in React Native, it will be executed when the execution time comes, or it will be rejected.

A promise is used to handle the asynchronous output of an executed operation. With promises, we can execute a code block until a non-block async request is complete. With this other operations can be kept running without any interruption.

States of executing promise in react

  1. Pending state when promises is in progress and not yet failed or succeeded
  2. Success state when promise is successfully executed
  3. Failure state when promise is failed and throw an error

Using Promise:

To use promises we have used then() which is called when a promise is resolved and catch() is called when the promise is rejected. catch() will catch an error while then() will pass the response.

useEffect(() =>{
let p = new Promise ((resolve,reject) => {
condition
if (condition){
setTimeout(() =>{
resolve("Promise is successful");
},3 *100);
}else{
reject ("Promise is rejected");
}

});
p.then((result) => {
console.log(result);
}).catch ((error) =>{
console.log(error);
});
},[]);

Chaining in Promises

Calling asynchronous requests multiple times is called Chaining. When the first promise is resolved or rejected, the second promise will start.

useEffect(() =>{
let p = new Promise ((resolve,reject) => {
condition
if (condition){
setTimeout(() =>{
resolve("Promise is successful");
},3 *100);
}else{
reject ("Promise is rejected");
}

});
p.then((result) => {
console.log(result);
}).then((newResult) => {
console.log(newResult);
}).catch((error) => {
console.log(error);
});
},[]);

Benefits of using Promises

  • Readability and maintainability: Promise code is more readable and maintainable than callback code. This is because Promise code is more declarative, while callback code is more imperative.
  • Error handling: Promise code makes it easier to handle errors. This is because Promises provide a way to reject promises, which can then be handled in a central location.
  • Chaining: Promises can be chained together, which makes it easy to perform multiple asynchronous operations in a sequence.

Promises in React Native

Promises can be used in React Native to handle any asynchronous operation, such as making API calls, fetching data from local storage, or performing animations.

Conclusion

Promises are a powerful tool for handling asynchronous code in React Native. They make code more readable, maintainable, and easier to debug.

If you like my content then please Follow me on Medium here and also follow me on GitHub and LinkedIn.

--

--

Tejas Khartude

Well, I work with Android using Kotlin and Java. I have developed keen interest in Python.