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));
2
Answers
First, your
loopVal
is 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
hi
functionIn your code you are setting loopVal to one every time you call the function. There is no state between each of the function calls. You can do it by using a closure that returns a function so you can maintain the variable’s state without having to make a global variable.