Correct way to write loops for promise.

后端 未结 13 1873
猫巷女王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:31

    Using the standard promise object, and having the promise return the results.

    function promiseMap (data, f) {
      const reducer = (promise, x) =>
        promise.then(acc => f(x).then(y => acc.push(y) && acc))
      return data.reduce(reducer, Promise.resolve([]))
    }
    
    var emails = []
    
    function getUser(email) {
      return db.getUser(email)
    }
    
    promiseMap(emails, getUser).then(emails => {
      console.log(emails)
    })
    

提交回复
热议问题