Promises in Node.js are used for handling asynchronicity. Here is an example of how you can use Promises:
Let’s say you have a function that reads a file and you want to run it asynchronously. Here is how you can do it using Promises.
```
const fs = require(‘fs’);
function readFileAsync(path, encoding) {
return new Promise(function(resolve, reject) {
fs.readFile(path, encoding, function(err, data){
if (err) {
return reject(err); // if there is an error, reject the Promise
}
resolve(data); // if successful, resolve the Promise
});
});
}
readFileAsync(‘path/to/your/file’, ‘utf8’)
.then(data => console.log(data)) // if the Promise is resolved, we’ll get the data here
.catch(err => console.log(err)); // if the Promise is rejected, we’ll get the error here
```
Here’s what this does:
1. We’re using the fs.readFile function in Node.js to read a file.
2. We’re working with the readFile function in a new Promise. This Promise takes in two parameters: resolve and reject.
3. If the readFile function has an error, we reject the Promise and pass the error into the reject function.
4. If the readFile function is successful, we resolve the Promise and pass the data into the resolve function.
5. We can then use .then to get the resolved data and .catch to handle any errors.
Remember, Promises give us a way to handle asynchronous operations in a synchronous-looking manner. Promises are in one of three states:
1. Pending: the Promise’s outcome hasn’t yet been determined, because the asynchronous operation that will produce its result hasn’t completed yet.
2. Fulfilled: the asynchronous operation has completed, and the Promise has a result, which is a value.
3. Rejected: the asynchronous operation failed, and the Promise will never be fulfilled. In the rejected state, a Promise has a reason that indicates why the operation failed.