Javascript:如何从Promise for循环中返回值?

时间:2019-05-21 13:34:23

标签: javascript promise return

在此示例中,如何返回sum的值?

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)
        ));
      }
    }

1 个答案:

答案 0 :(得分:0)

我不确定您在寻找什么,但这将是兑现承诺的正确方法:

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()

不使用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))