How to create a Promise in javascript
Promise creation is using new operator with Promise Constructor. Promise constructor contains resolve and reject that are functions.
const promise = new Promise((resolve, reject) => {
});
Here is an example
const promise = new Promise((resolve, reject) => {
resolve("hello");
});
promise.then((res) => {
console.log("then function called",res);
});
promise.catch((err) => {
console.log("catch function called");
});
const promise = new Promise((resolve, reject) => {
reject(new Error("Error message"));
});
promise.then((res) => {
console.log("then function called",res);
});
promise.catch((err) => {
console.log("catch function called");
});