Promises in ES6 are used to handle asynchronous operations by keeping track of whether a certain event has happened. If that event has happened, it determines what happens next. Promises return a value which is either a resolved value or a reason why it’s rejected.
Here’s how you can create a promise in Node.js:
```
let isItTrue = true;
let promise = new Promise(function(resolve, reject) {
if (isItTrue) {
resolve(“The promise is resolved”);
} else {
reject(“The promise is rejected”);
}
});
promise.then((message) => {
console.log(message); // will print “The promise is resolved” if isItTrue = true
}).catch((message) => {
console.log(message); // will print “The promise is rejected” if isItTrue = false
});
```
In this example,
- `let promise = new Promise(function(resolve, reject))` creates a new promise instance. The promise constructor takes one argument, a callback function. The callback function takes two arguments, resolve and reject, which are both functions.
- If something went well, then you want to call resolve with some value. If something went wrong, call reject with some reason.
- You can use the `.then()` method to schedule code that will run when the promise is resolved and the `.catch()` method to handle any errors.
You could also use Promise chaining:
```
let promise1 = new Promise(function(resolve, reject) {
setTimeout(() => {
resolve(“Resolved!”);
}, 2000);
});
let promise2 = new Promise(function(resolve, reject) {
setTimeout(() => {
resolve(“Resolved again!”);
}, 2000);
});
promise1.then((message) => {
console.log(message);
return promise2;
}).then((message) => {
console.log(message);
}).catch((message) => {
console.log(message);
});
```
In promise chains, the `then` function gets placed on the end of the original Promise and will execute after the original Promise has either resolved or rejected.