skip to Main Content

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


  1. 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 function

    const hi = function(val, delay) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log("Resolved Successfully", val);
          resolve(val+1);
        }, delay)
      })
    }
    
    const bye = async() => {
      var val = 1;
      val = await hi(val, 1000);
      val = await hi(val, 1000);
      console.log("Final value", val);
      return "bye";
    }
    
    bye().then((value) => console.log(value));
    Login or Signup to reply.
  2. In 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.

    const hi = (function() {
    
      let loopVal = 1;
      
      return function(delay) {
        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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search