DEV Community

Rajasekar Thangavel
Rajasekar Thangavel

Posted on • Edited on

How to use promise in nodejs

Where we need promise

When the time of using javascipt code if there is delay in output for example if you are developing student management system with role number you need to access particular fees details but accessing roll number is time taking process in the case need to use promise

Promise definition

const delay = new Promise(resolve => {
    setTimeout(() => {
        resolve();
    }, 90000);
});
Enter fullscreen mode Exit fullscreen mode

Promise calling function

delay.then(()=> {
    console.log("Done Waiting");
})
Enter fullscreen mode Exit fullscreen mode

Promise in loop

const delays = [122, 100, 2000, 600];

const delay = (millisec) => {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(millisec);
            resolve(millisec)
        }, millisec);
    })
}

Promise.all(
    delays.map(d => delay(d))
).then(() => { console.log("-----------") })

Enter fullscreen mode Exit fullscreen mode

Ref : https://medium.com/developer-rants/running-promises-in-a-loop-sequentially-one-by-one-bd803181b283
https://stackoverflow.com/questions/65167410/wait-for-array-map-iterations-in-promise-all

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay