7 Steps to JavaScript Promises: A Beginner’s Guide
Promises are an essential feature of JavaScript that help manage asynchronous operations and handle their results. They provide a way to write cleaner and more readable code when dealing with tasks that may take some time to complete, such as making API requests or executing time-consuming operations.
In this blog post, we’ll explore the basics of promises and demonstrate their usage through code examples.
Let’s get started!!! 🚀🚀
Contents
- Creating a Promise
- Resolving a Promise
- Chaining Promises
- Executing Functions on Resolve
- Handling Rejection with Catch
- Chaining Multiple Promises
- Using JSONPlaceholder API for Testing
1. Creating a Promise
const count = false;
let countValue = new Promise(function(resolve, reject) {
if (count) {
resolve('There is a count value.');
} else {
reject('There is no count value.');
}
});
In this example, we create a promise countValue
that represents an asynchronous operation. If count
is true
, the promise is resolved with the message "There is a count value." Otherwise, it is rejected with the message "There is no count value." You can console.log(countValue)
statement to see the result.
2. Resolving a Promise
let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error('Whoops')), 1000);
});
Here, we create a promise promise
that resolves after a delay of 5 seconds (5000
milliseconds). Once resolved, it logs the success message "done" to the console.
3. Rejecting a Promise
let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error('Whoops')), 1000);
});
In this example, the promise promise
is rejected after a delay of 1 second (1000
milliseconds) with an Error
object containing the message "Whoops". You can handle the rejection using the catch
method, which we'll see in example 5.
3: Chaining Promises
const promise = doSomething();
const promise2 = promise2.then(successCallback, failureCallback);
// simplified
const promise3 = doSomething().then(successCallback, failureCallback);
Promises can be chained together to perform a sequence of asynchronous tasks. In this example, doSomething()
represents the first asynchronous task, which returns a promise. Then, we chain the then
method to handle the resolved value (successCallback
) or the rejected value (failureCallback
) of the promise
4: Executing Functions on Resolve
let exampleTask = new Promise(function(resolve, reject) {
resolve('Promise resolved');
});
exampleTask.then(function successValue1(result){
console.log(result);
}).then(function successValue2(){
console.log('You can call multiple functions this way');
});
In this example, the promise exampleTask
is resolved successfully, and we use the then
method to execute the successValue1
function, which logs the resolved result. We can also chain multiple then
methods to call multiple functions sequentially.
5: Handling Rejection with Catch
let exampleTask = new Promise(function(resolve, reject) {
reject('Promise rejected');
});
exampleTask.then(function successValue1(result){
console.log(result);
}).catch(function errorValue(result){
console.log(result);
});
In this example, the promise exampleTask
is rejected, and we handle the rejection using the catch
method. The errorValue
function is executed, logging the rejected result. Using catch
allows us to handle errors in a centralized manner.
6: Using Finally
let countValue = new Promise(function(resolve, reject) {
reject("Promise rejected");
});
countValue.then((success) => {})
.catch((error) => {
console.log(error);
})
.finally(function greet(){
console.log("This code is executed.");
});
The finally
method is used to execute a function regardless of whether the promise is resolved or rejected. In this example, the greet
function is always executed, regardless of the promise result.
7: Chaining Multiple Promises
examplePromiseTask()
.then(function (result) {
return secondTask();
})
.then(function (result) {
return thirdTask();
})
.catch(function (err) {
// Handle any errors here
});
Promises can be chained together to perform multiple asynchronous tasks sequentially. In this example, examplePromiseTask
is executed first, followed by secondTask
, and then thirdTask
. If any promise in the chain is rejected, the catch
method is called to handle the error.
Using JSONPlaceholder API for Testing
To demonstrate the usage of promises with a real API, you can integrate the JSONPlaceholder API into your code examples. JSONPlaceholder provides a set of mock endpoints for testing purposes.
For example, you can replace doSomething()
in Example 3 with an API call:
function doSomething() {
return fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json());
}
Similarly, you can modify other examples to include API requests and handle the returned data or errors accordingly.
Conclusion
Promises are a powerful tool in JavaScript for managing asynchronous operations. They simplify the handling of asynchronous code and make it easier to reason about complex flows. By understanding and practicing with promises, you can write more efficient and maintainable code in JavaScript.
Happy coding!💻
Also if you need more help check this video on Learn JavaScript Promises in 19 minutes (For Beginners) from Sonny Sanga on Youtube
Thanks for your time ♥
Where to find Me 👇
Here on Medium ♥️
You can also find me also 👉 Github https://github.com/Onlynfk/
Instagram / LinkedIn