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);
CodePudding user response:
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);
