-
Notifications
You must be signed in to change notification settings - Fork 0
How to create Promise
Daisho Komiyama edited this page Mar 2, 2020
·
5 revisions
Today, I realized I've been using Promise without knowing how to create it. This is how I create Promise and how I consume it in Node. In this example, I'm skipping to bring path module but it should always be there whenever you use file system module.
const fs = require("fs");
//Creating Promise
const read = () => {
return new Promise((resolve, reject) => {
fs.readFile("./package.json", (error, data) => {
return error ? reject(error) : resolve(data.toString());
});
});
};
//Consuming Promise
read()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
//Creating Promise.all
const readAll = () => {
const promises = [read(), read(), read()];
return Promise.all(promises);
};
//Consuming Promise.all
readAll()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});