How to synchronize a sequence of promises?

后端 未结 6 811
醉梦人生
醉梦人生 2020-11-22 09:05

I have an array of promise objects that must be resolved in the same sequence in which they are listed in the array, i.e. we cannot attempt resolving an element till the pre

6条回答
  •  逝去的感伤
    2020-11-22 09:45

    In my opinion, you should be using a for loop(yes the only time I would recommend a for loop). The reason is that when you are using a for loop it allows you to await on each of the iterations of your loop where using reduce, map or forEach with run all your promise iterations concurrently. Which by the sounds of it is not what you want, you want each promise to wait until the previous promise has resolved. So to do this you would do something like the following.

    const ids = [0, 1, 2]
    const accounts = ids.map(id => getId(id))
    const accountData = async() => {
       for await (const account of accounts) {
           // account will equal the current iteration of the loop
           // and each promise are now waiting on the previous promise to resolve! 
       }
    }
    
    // then invoke your function where ever needed
    accountData()
    

    And obviously, if you wanted to get really extreme you could do something like this:

     const accountData = async(accounts) => {
        for await (const account of accounts) {
           // do something
        }
     }
    
     accountData([0, 1, 2].map(id => getId(id)))
    

    This is so much more readable than any of the other examples, it is much less code, reduced the number of lines needed for this functionality, follows a more functional programming way of doing things and is using ES7 to its full potential!!!!

    Also depending on your set up or when you are reading this you may need to add the plugin-proposal-async-generator-functions polyfill or you may see the following error

    @babel/plugin-proposal-async-generator-functions (https://git.io/vb4yp) to the 'plugins' section of your Babel config to enable transformation.

提交回复
热议问题