DEV Community

Rajasekar Thangavel
Rajasekar Thangavel

Posted on • Updated 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

Top comments (0)