0

How do I return the value of sum in this example?

function slowFunction(par) {
      sum = 0
      for (let i = 0, p = Promise.resolve(); i < 5; i++) {
        p = p.then(_ => new Promise(resolve =>
          setTimeout(function () {
            sum += i ;
            console.log(i);
            resolve();
          }, Math.random() * 1000)
        ));
      }
    }
fatecasino
  • 49
  • 2
  • 7

1 Answers1

0

I'm not sure what you're looking for, but this would be the correct way to wrap the promise:

function slowFunction(par) {
    return new Promise(resolve => {
        var sum = 0
        for (let i = 0; i < 5; i++) {
            setTimeout(function () {
                sum += i ;
                resolve(sum);
            }, Math.random() * 1000)
        }
    })   
}

async function main() {
    const i = await slowFunction()
    console.log(i) 
}

main()

Without using asyc/await:

function slowFunction(par) {
    return new Promise(resolve => {
        var sum = 0
        for (let i = 0; i < 5; i++) {
            setTimeout(function () {
                sum += i ;
                resolve(sum);
            }, Math.random() * 1000)
        }
    })   
}

slowFunction().then(value => console.log(value))
Kobe
  • 6,226
  • 1
  • 14
  • 35