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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs