The list of promises is output sequentially and each asynchronous operation is executed in parallel

The core of this problem is the bright spot

  1. Each asynchronous operation is run concurrently
  2. According to the order of the array, output the result

  function createPromise(value, time) {
    
    
    return new Promise((resolve, reject) => {
    
    
      setTimeout(() => {
    
    
        resolve(value)
      }, time)
    })
  }

  let list = [
    createPromise(1, 1000),
    createPromise(2, 6000),
    createPromise(3, 4000),
    createPromise(4, 3000),
  ];

  let last = -1;

  function print(data, index) {
    
    
    // 前边的输出 没输出完,直接return
    if (index - last === 1) {
    
    
      // 检查后边的,后边没有,退出,有,输出
      while (data[index] !== undefined) {
    
    
        console.log(data[index])
        last = +index;
        index++;
      }
    }
  }

  let proxy = new Proxy({
    
    }, {
    
    
    set(target, p, value, receiver) {
    
    
      target[p] = value;
      print(target, p);
    }
  });

  function run(promiseList) {
    
    
    for (let a = 0; a < promiseList.length; a++) {
    
    
      let p = promiseList[a];
      p.then(r => {
    
    
        proxy[a] = r;
      })
    }
  }

  run(list)

Guess you like

Origin blog.csdn.net/qq_29334605/article/details/114534524