Create new promisein node
In Node.js, you can create a new promise using the Promise
constructor. Here's an example:
const promise = new Promise((resolve, reject) => {
// code that may take some time to complete
setTimeout(() => {
resolve("Promise resolved!"); // or reject("Promise rejected!")
}, 2000);
});
In this example, we create a new promise using the Promise
constructor. The constructor takes a callback function as an argument, which is called when the promise is created. This callback function is responsible for resolving or rejecting the promise.
The callback function takes two arguments: resolve
and reject
. resolve
is a function that resolves the promise with a value, and reject
is a function that rejects the promise with a reason.
In this example, we use setTimeout
to simulate some asynchronous operation that takes 2 seconds to complete. When the operation is complete, we call resolve
to resolve the promise with the string "Promise resolved!".
You can then use the promise to handle its outcome using then
and catch
methods:
promise.then((result) => {
console.log(result); // prints "Promise resolved!"
}).catch((error) => {
console.error(error);
});
Note that you can also create a promise using the Promise.resolve
or Promise.reject
methods, which create a resolved or rejected promise immediately:
const resolvedPromise = Promise.resolve("Hello");
const rejectedPromise = Promise.reject(new Error("Error!"));
These methods are useful when you need to create a promise that is already resolved or rejected.