Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for JavaScript Promise methods Explained!
Bhavesh Kasturi
Bhavesh Kasturi

Posted on

     

JavaScript Promise methods Explained!

What is Promise?

The Promise is a simply improved version of callbacks, and JavaScript's Promise is effectively the same as Promise in real life. You make a promise to do something, and either does it and succeed or do not do it and fail. That is how JavaScript's Promise works.
A Promise is essentially saying, "Hey, I'm going to execute some code, and if I'm successful, I'll let you know and give you the result," and "If I'm unsuccessful, I'll let you know and just tell you the error that goes with that code."

constpromise=newPromise((resolve,reject)=>{// resolve- happens when you successfully complete the promise// reject - happens when you failed to complete the promiseconstsum=10+10if(sum===20){resolve("Success");}else{reject("Error");}});promise.then(message=>{console.log(message);}).catch(message=>{console.log(message);})// Output -> Success
Enter fullscreen modeExit fullscreen mode

Let's look at Promise methods

Promise.all()

Promise.all() is used to run multiple promises, we need to pass an array of different promises, and then we can do things based on whether they all fail or some of them fail or they all succeed or some of them succeed.

resolve() → returns a successful promise.

reject() → returns a failed promise.

Promise.all([Promise.resolve("1"),Promise.resolve("2"),Promise.resolve("3"),]).then(messages=>{console.log(messages)})// Output -> ["1", "2", "3"]
Enter fullscreen modeExit fullscreen mode

In the above code snippet, all threePromise have been successfully resolved and they have the message "1", "2", "3" inside of them. The messages array is the return value of all our promises in order from top to bottom.

Promise.all([Promise.resolve("1"),Promise.resolve("2"),Promise.reject("Error on 3"),Promise.reject("Error on 4"),]).then(messages=>{console.log(messages)}).catch(error=>{console.error(error)})// Output -> Error on 3
Enter fullscreen modeExit fullscreen mode

In the above code snippet only the rejected value is printed from the.catch() block and nothing gets printed from the.then() block.

This happens because thePromise.all() only calls.then() when every singlePromise inside it succeeds or is resolved. If one of them fails it will call.catch and print the result of the first failed or rejectedPromise.


Promise.any()

→ It takes the array of multiple promises and It returns any of the firstPromise that gets succeeds or resolved, you can imagine a bunch of differentPromise taking various amount of time to execute, the first one to get executed will return the value in.then()

Promise.any([Promise.resolve("1"),Promise.reject("Error on 2"),Promise.reject("Error on 3"),Promise.resolve("4"),]).then(message=>{console.log(message)}).catch(error=>{console.error(error)})// Output -> 1Promise.any([Promise.reject("Error on 1"),Promise.reject("Error on 2"),Promise.resolve("3"),Promise.resolve("4"),]).then(message=>{console.log(message)}).catch(error=>{console.error(error)})// Output - 3
Enter fullscreen modeExit fullscreen mode

Promise.race()

→ It takes an array of multiple promises, It is likePromise.any() but instead of getting the first promise that succeeds,Promise.race() returns the firstPromise that finishes whether or not it succeeds or fails.

Promise.race([Promise.reject("Error on 1"),Promise.reject("Error on 2"),Promise.resolve("3"),Promise.resolve("4"),]).then(message=>{console.log(message)}).catch(error=>{console.error(error)})// Output -> Error on 1Promise.race([Promise.resolve("1"),Promise.resolve("2"),Promise.reject("Error on 3"),Promise.reject("Error on 4")]).then(message=>{console.log(message)}).catch(error=>{console.error(error)})// Output -> 1
Enter fullscreen modeExit fullscreen mode

The code above is notasynchronous it is getting executed from top to bottom but if were to imagine it has the timeout and it took a given of time to succeed or fail. The example is given below.

Promise.race([Promise.resolve("1"),// 100 msPromise.resolve("2"),// 400 msPromise.reject("Error on 3"),// 200 msPromise.reject("Error on 4")// 20 ms]).then(message=>{console.log(message)}).catch(error=>{console.error(error)})// Output -> Error on 4
Enter fullscreen modeExit fullscreen mode

The above code snippet will printError on 4 because it will be the first one to finish its execution.


Promise.allSettled()

→ It takes an array of multiple promises,Promise.allSettled() waits for all the Promises to finish whether they get rejected or they get fulfilled it doesn't matter it waits for every singlePromise to finish.

Promise.allSettled([Promise.resolve("1"),Promise.resolve("2"),Promise.reject("Error on 3"),Promise.reject("Error on 4")]).then(messages=>{console.log(messages)}).catch(error=>{console.error(error)})/* Output -> (4) [{…}, {…}, {…}, {…}]0: {status: "fulfilled", value: "1"}1: {status: "fulfilled", value: "2"}2: {status: "rejected", reason: "Error on 3"}3: {status: "rejected", reason: "Error on 4"}length: 4*/
Enter fullscreen modeExit fullscreen mode

As you can seePromise.allSettled() prints the 4 objects and
the object contains thestatus which isrejected orfullfilled.
reason if thestatus isrejected
value if thestatus isfulfilled.

Promise.allSettled([Promise.reject("Error on 1"),Promise.reject("Error on 2"),Promise.reject("Error on 3"),Promise.reject("Error on 4")]).then(messages=>{console.log(messages)}).catch(error=>{console.error(error)})/* Output -> (4) [{…}, {…}, {…}, {…}]0: {status: "rejected", reason: "Error on 1"}1: {status: "rejected", reason: "Error on 2"}2: {status: "rejected", reason: "Error on 3"}3: {status: "rejected", reason: "Error on 4"}length: 4*/
Enter fullscreen modeExit fullscreen mode

In the above code snippet as you can see it still calls the.then() even after all thePromise got rejected, becausePromise.allSettled() will always call.then even if thePromise gets fulfilled or rejected.

Thank you for making it till the end!

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
vukas profile image
Aleksandar Vukasovic
Recently entered the IT World. Now looking forward to bring my passion for web development in my projects, and keeping myself updated with the upcoming trends.
  • Location
    Belgrade,Serbia
  • Education
    BIT Belgrade, Bootcamp
  • Joined

Great article!
Have you done 2021 updated version with Promise.any()?

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Frontend @ProfitWheel
  • Location
    Mumbai
  • Joined

More fromBhavesh Kasturi

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp