CARVIEW |
What are promises in JavaScript?
In JavaScript, callback functions were initially used to handle asynchronous operations. However, callbacks were limited in terms of functionality and often led to confusing code, so, promises were introduced to cater to these problems. According to MDN, “the Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.”
A promise object has one of three states:
- pending: is the initial state.
- fulfilled: indicates that the promised operation was successful.
- rejected: indicates that the promised operation was unsuccessful.
Code
Creating a simple promise
- A
promise
is created using a constructor that takes a call back function with two arguments (line 1). - The code needed to perform the promised task is written. In this example, it is assumed that the code executes successfully (line 2).
- If the task is successful, the promise is resolved. In this example, the optional parameter “The promised task was performed successfully” is passed (lines 4-5).
- If the task is unsuccessful, then the promise is rejected. In this example, an optional parameter is passed (lines 6-7).
- The
then()
method is called when the promise is resolved, and thecatch()
method is called if the promise is rejected or if there was an error during the code execution (lines 10-11).
Using Promise.all()
The Promise.all()
method returns a single promise that resolves when all of the passed-in promises have resolved. It rejects if one of the promises is rejected.
Using Promise.race()
The Promise.race()
method returns a promise that resolves or rejects as soon as one of the promises resolves or rejects. The fromRes
method contains the value from the promise that is resolved first.
Relevant Answers
Explore Courses
Free Resources