JS-Promises
Promises are used to handle asynchronous operations in a more cleaner and manageable way in contrast to the traditional callback-based operations.
Asynchronous operations:
Asynchronous operations in computing are tasks that are initiated and proceed in the background, allowing the main program to continue running without waiting for the tasks to be completed. As we are aware JS is a single-threaded-language.
Some examples of asynchronous operations are :
Network Requests
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Timers
setTimeout(() => {
console.log('This message is delayed by 2 seconds.');
}, 2000);
File I/O
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
Event Listeners
document.getElementById('button').addEventListener('click', () => {
console.log('Button clicked!');
});
Web Workers
const worker = new Worker('worker.js');
worker.onmessage = (event) => {
console.log('Message from worker:', event.data);
};
worker.postMessage('Hello, worker!');
Promises and how to use them
First I created a promise and kept it in a constant and after applied the .then() to it.
const promiseOne = new Promise(function(resolve,reject){
setTimeout(function(){
console.log('Async task is complete ');
resolve()
},1000)
})
promiseOne.then(function(){ // then is related to resolve , the function in the promise will return here
console.log("promise done")
})
// It can also be done in this way as well
new Promise(function(resolve, reject){
setTimeout(function(){
resolve();
console.log("Async2");
}, 1000);
}).then(function(){
console.log("This is it");
});
You can pass objects as well :
const promise3 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve({ username: "Chai", email: "chai@example" });
}, 1000);
});
promise3.then(function(user){
console.log(user);
});
We use .finally() as well to give a last function or an operation even if the operation is rejected .
const promise4 = new Promise(function(resolve, reject){
setTimeout(function(){
let error = false;
if (!error) {
resolve({ user: "Hitesh", pass: "asd" });
} else {
reject('Error: something went wrong');
}
}, 1000);
});
promise4.then((users) => {
console.log(users);
}).then((user) => {
console.log(user);
}).catch(function(error){
console.log(error);
}).finally(() => {
console.log("The promise is either resolved or rejected");
});
Using a try-catch block we can catch errors and this is very helpful in large-scale deployments to identify and locate errors
const promise5 = new Promise(function(resolve, reject) {
setTimeout(function(){
let error = true;
if (!error) {
resolve({ username: "Aman", pass: "asd" });
} else {
reject('Js went wrong');
}
}, 1000);
});
// async/await. Remember that promise is an object
async function consumePromise5() {
try {
const response = await promise5;
console.log(response);
} catch (error) {
console.log(error);
}
}
consumePromise5();
FETCH API
The fetch
API is a modern interface for making HTTP requests in JavaScript. It returns a Promise that resolves to the Response
object representing the response to the request.
Using async/await
async function getAllUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json(); // remember to put await in here
console.log(data);
} catch (error) {
console.log(error);
}
}
getAllUsers();
Function Declaration: The function
getAllUsers
is declared asasync
, which allows the use of theawait
keyword inside it.Try/Catch Block: The
try
block is used to attempt the asynchronous operation, and thecatch
block is for handling any errors that occur during the execution.Fetching Data:
await fetch('
https://jsonplaceholder.typicode.com/users
')
: Thefetch
function is called with the URL. Theawait
keyword pauses the execution of thegetAllUsers
function until the Promise returned byfetch
resolves. This ensures thatresponse
contains theResponse
object.await response.json()
: Once the fetch Promise resolves,response.json()
is called to parse the JSON body of the response. Again,await
is used to wait for the parsing to complete, sodata
contains the parsed JSON object.
Logging Data: The parsed JSON data is logged to the console.
Error Handling: If any error occurs during the fetch or the JSON parsing, it is caught in the
catch
block and logged to the console.