I had tried to increment the variable loopVal inside the promise but I am unable to increment it. How can I do that?
const hi = function(delay) {
let loopVal = 1;
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Resolved Successfully", loopVal);
resolve();
loopVal++;
}, delay)
})
}
const bye = async() => {
await hi(1000);
await hi(1000);
return "bye";
}
bye().then((value) => console.log(value));
First, your
loopValis local to the function, its changes are discarded as soon as the function terminates.Second, you don't return the changed value from the promise.
One of possible approaches is to have this variable in a scope where it can be both used as an argument and a return value from your
hifunction