How to create Promise
Daisho Komiyama edited this page Feb 7, 2022
·
5 revisions
I've been using Promise without knowing how it is built. This is a note for me about Promise creation. I'm using this block of code with the archiving-app
project.
In this example, I'm skipping to bring path module but it should always be there whenever you use the 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());
});
});
};
// using 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);
};
// using Promise.all
readAll()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});