How to synchronize a sequence of promises?

后端 未结 6 899
醉梦人生
醉梦人生 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:46

    I suppose two approaches for handling this question:

    1. Create multiple promises and use the allWithAsync function as follow:
    let allPromiseAsync = (...PromisesList) => {
    return new Promise(async resolve => {
        let output = []
        for (let promise of PromisesList) {
            output.push(await promise.then(async resolvedData => await resolvedData))
            if (output.length === PromisesList.length) resolve(output)
        }
    }) }
    const prm1= Promise.resolve('first');
    const prm2= new Promise((resolve, reject) => setTimeout(resolve, 2000, 'second'));
    const prm3= Promise.resolve('third');
    
    allPromiseAsync(prm1, prm2, prm3)
        .then(resolvedData => {
            console.log(resolvedData) // ['first', 'second', 'third']
        });
    
    1. Use the Promise.all function instead:
      (async () => {
      const promise1 = new Promise(resolve => {
        setTimeout(() => { console.log('first');console.log(new Date());resolve() }, 1000)
      })
    
      const promise2 = new Promise(resolve => {
        setTimeout(() => {console.log('second');console.log(new Date());  resolve() }, 3000)
      })
    
      const promise3 = new Promise(resolve => {
        setTimeout(() => { console.log('third');console.log(new Date()); resolve() }, 7000)
      })
    
      const promises = [promise1, promise2, promise3]
    
      await Promise.all(promises)
    
      console.log('This line is shown after 7000ms')
    })()
    

提交回复
热议问题