promises in js
Promises in JavaScript
Asynchronous programming is an integral part of modern web development. Promises are used to handle asynchronous operations in JavaScript. It is an alternative to callbacks which can result in callback hell. Promises represent a value that is not available yet but will be resolved in the future.
Creating Promises
To create a promise, use the Promise constructor, which takes a function with two parameters, resolve and reject. The resolve function is called when the promise is fulfilled, and the reject function is called when the promise is rejected. Here's an example:
const promise = new Promise((resolve, reject) => {
// asynchronous operation
// resolve(value) or reject(error)
});
Chaining Promises
One of the key features of promises is chaining. This means that you can attach multiple .then() methods to a promise, each one returning another promise. Here's an example:
const promise = new Promise((resolve, reject) => {
resolve('First Value');
});
promise.then((value) => {
console.log(value); // First Value
return 'Second Value';
}).then((value) => {
console.log(value); // Second Value
});
Handling Errors
Promises can be rejected, and you can handle those errors using the .catch() method. The .catch() method should be called after all the .then() methods. Here's an example:
const promise = new Promise((resolve, reject) => {
reject('Error Message');
});
promise.then((value) => {
console.log(value);
}).catch((error) => {
console.error(error); // Error Message
});
Async/Await
Async/await is a feature that was introduced in ES2017. It allows you to write asynchronous code that looks synchronous. Async functions always return a promise. You can use the await keyword to wait for a promise to resolve. Here's an example:
async function myAsyncFunction() {
const promise = new Promise((resolve, reject) => {
resolve('Value');
});
const value = await promise;
console.log(value); // Value
}
myAsyncFunction();
In conclusion, promises are an essential part of modern JavaScript development. They provide a way to handle asynchronous operations in a more organized and readable way than using callbacks.