Execute promises map sequentially

前端 未结 3 1029
梦谈多话
梦谈多话 2021-01-18 22:12

I have written a function that is being called in a loop (map) and that function is using promises. Now, I want that function to run synchronously and exit before its next i

3条回答
  •  遥遥无期
    2021-01-18 22:39

    Here is what running Promises sequentially would look like when using .reduce() in combination with async/await:

    async function main() {
    
      const t2 = (v) => Promise.resolve(v*2)
      const arr1 = [1,2,3,4,5];
      
      const arr1_mapped = await arr1.reduce(async (allAsync, val) => {
        const all = await allAsync
        all.push(await t2(val) /* <-- your async transformation */) 
        return all
      }, Promise.resolve([]))
    
      console.log(arr1_mapped)
    
    }
    
    main()

提交回复
热议问题