Skip to content

How to create Promise

Daisho Komiyama edited this page Feb 7, 2022 · 5 revisions

Today, I realized I've been using Promise without knowing how to create it. So this is how I create Promise and how I consume it in Node. I'm using this block of code below with archiving-app repository. 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());
        });
    });
};

// 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);
    });
Clone this wiki locally