The Essential Guide to Using Promise in JavaScript
source link: https://hackernoon.com/the-essential-guide-to-using-promise-in-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
@taimoorTaimoor Sattar
I am an independent designer and developer.
Promise in JavaScript is the way to wait for a certain action to process or complete. The promise has the following states:
Pending: incomplete (initial state), neither fulfilled nor rejected.
Fulfilled: The process was successfully completed.
Rejected: The process failed.
So, where the promise is useful? We can use promise in JavaScript in a different situation. For example:
Wait for the response from the HTTP request
async and await function
Schedule Task e.g. setTimeout and setInterval
We can use fetch in JavaScript to retrieve the data from a certain API endpoint. The fetch in JavaScript is a promise that returns the data if the request is successfully processed.
Let's take an example. We have 1st person that's giving the promise and 2nd person that's waiting for the promise to fulfill.
In JavaScript, we can define the promise as below:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
if(Math.random() > 0.5){
resolve('foo');
}else{
reject("Exception!")
}
}, 300);
});
In the above, we define the promise that waits for 0.3 seconds and returns the pass or fails message based on the boolean logic (true or false).
Now, to wait for the promise to complete, we can write code in JavaScript as below:
myPromise
myPromise
.then(value => { return value + ' and bar'; })
.then(value => { console.log(value) })
.catch(err => { console.log(err) })
.finally(() => {
console.log('Promise completed');
});
In the above code, the following callback function runs:
.then
: Executes when the process is successfully completed
.catch
: Executes when the process is failed
.finally
: execute at every condition
Moving further... Let's say, we have more than one person that is giving the promise. We can define in JavaScript as below:
const promise1 = Promise.resolve("great");
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 300, 'Yesss!!!');
});
We can use Promise.all
that returns a promise which resolves after all of the given promises have either been fulfilled or rejected. We can write in JavaScript as below:
Promise.all([promise1, promise2]).then((values) => {
console.log(values);
})
.catch(error => {
console.error(error.message)
});
The above code will log the following in the console:
["great","Yesss!!!"]
The previous example works OK if all the promises resolve successfully. But... let's say, If one of the promises is rejected, the overall Promise.all will be rejected even if every other promise is resolved successfully.
Let say, If we are waiting for many promises. Some promises got fulfilled and some are rejected. In JavaScript, we can define promise as below:
var p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('p1_delayed_resolution1'), 1000);
});
var p2 = new Promise((resolve, reject) => {
reject(new Error('p2_immediate_rejection'));
});
In Promise.all
, we can use the .catch
statement to handle the error of each promise.
Promise.all([
p1.catch(error => { return error }),
p2.catch(error => { return error }),
]).then(values => {
console.log(values[0]) // "p1_delayed_resolution"
console.error(values[1]) // "Error: p2_immediate_rejection"
})
We’ve covered the basics of promise in Javascript. To learn more about Javascript, you can visit here.
Recommend
-
4
The Essential Protobuf Guide for Python Are you already making use of Protobuf for serializing your data? If you aren't, read this post to find out what you are missing out on!
-
7
After getting the hang of async programming in javascript, you might quickly find you need to wait for multiple async tasks to happen. Enter Promise.all! A Single Promise To start out, let’s do a simple fetch requ...
-
6
@msokolaMatt SokolaSenior Software Engineer based in Abu Dhabi, United Arab EmiratesThis post will show you how to build the Feature Toggle mechanism in your...
-
4
Using the Promise all(), race(), allSettled() and any() in Javascript With the many options for solving multiple multiple concurrent promises things can get a bit confusing. Let's see the options one by one: ...
-
4
Not FoundYou just hit a route that doesn't exist... the sadness.LoginRadius empowers businesses to deliver a delightful customer experience and win customer trust. Using the LoginRadius Identity...
-
9
The Best JavaScript Tools in 2022: An Essential Guide to Better DevelopmentApril 12th 2022 new story0
-
4
Introduction: What are JavaScript functions? A JavaScript
-
3
This tutorial will teach you how to use promises to wait in JavaScript. In this tutorial, I will teach you about the Promise.all() and Promise.allSettled() methods and how you can use them to work with multiple pro...
-
10
JavaScript Interview Question
-
5
Deferred JavaScript promises using Promise.withResolversPublished: 2024.01.25 · 2 minutes readIf you have been building for the Web platform long enough, you may remember
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK