Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Promise based counter

I am new to learning JavaScript and so have begun understanding promises.
I have written a simple code that logs the value passed to promise function as parameter, after setTimeout goes off.
If i need to create a counter using the same code, is there a way I can do that?

function hello(a, b) {
    let promise = new Promise((res, rej) => {
        setTimeout(() => {
            res(a);
        }, b);
    }).then((result) => {
        console.log(`Result: ${result}`);
    });
}
hello(5, 1500);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you want to get the numbers of times hello’s promise resolved.

Simply add a count variable and increment each time promise resolved

let count = 0;
function hello(a, b) {
    let promise = new Promise((res, rej) => {
        setTimeout(() => {
            res(a);
        }, b);
    }).then((result) => {
        count++;
        console.log(`Result: ${result}, Count: ${count}`);
    });
}
hello(5, 1500);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading