In Node.js, promises are a way to handle asynchronous operations.
They provide a cleaner alternative to callbacks and make it easier to write asynchronous code that's easier to read, write, and maintain.
const myPromise = new Promise((resolve, reject) => {
// Async operation
setTimeout(() => {
// Resolve the promise
resolve('Operation completed successfully!');
// Or reject the promise
// reject(new Error('Operation failed!'));
}, 2000);
});
myPromise
.then((result) => {
console.log(result); // Output: "Operation completed successfully!"
})
.catch((error) => {
console.error(error); // Output: "Operation failed!"
});
© www.thecoderjob.com. All Rights Reserved. Designed by HTML Codex