Correct way to write loops for promise.

后端 未结 13 1927
猫巷女王i
猫巷女王i 2020-11-22 15:20

How to correctly construct a loop to make sure the following promise call and the chained logger.log(res) runs synchronously through iterat

13条回答
  •  广开言路
    2020-11-22 15:37

    Given

    • asyncFn function
    • array of items

    Required

    • promise chaining .then()'s in series (in order)
    • native es6

    Solution

    let asyncFn = (item) => {
      return new Promise((resolve, reject) => {
        setTimeout( () => {console.log(item); resolve(true)}, 1000 )
      })
    }
    
    // asyncFn('a')
    // .then(()=>{return async('b')})
    // .then(()=>{return async('c')})
    // .then(()=>{return async('d')})
    
    let a = ['a','b','c','d']
    
    a.reduce((previous, current, index, array) => {
      return previous                                    // initiates the promise chain
      .then(()=>{return asyncFn(array[index])})      //adds .then() promise for each item
    }, Promise.resolve())
    

提交回复
热议问题