Using the generator function to implement asynchronous task queue

Time:2021-12-4
var genAsyncTask2 = (val, time) => {
      return () => {
        return new Promise(function (resolve, reject) {
          let timer = setTimeout(() => {
            clearTimeout(timer);
            resolve(val);
          }, time);
        });
      }
    }
  
    //Task queue
    var taskArr = [
      Genasynctask2 ('the first asynchronous task, the time is 2 seconds', 2000), genasynctask2 ('the second asynchronous task, the time is 1 second ', 1000),
      Genasynctask2 ('the third asynchronous task, time 0.8 seconds', 800), genasynctask2 ('the fourth asynchronous task, time 2.5 seconds', 2500)
    ];
  
  
    function *genFun(taskArr){
      for(let i = 0 , len = taskArr.length; i < len; i++){
        yield taskArr[i]().then(res => {
          console.log('genSync', res);
          return res;
        });
      }
    }
  
    /**
     *Automatically execute the next of the generate function and ensure the execution order
     *@ param generatefn generate function
     *@ param params parameters required to execute the generate function
     */
    function generateAutoExec(generateFn, ...params) {
      var g = generateFn(...params);
  
      var next = function (res) {
        if (res.done || typeof res.value == 'undefined') return res.value;
        res.value.then((data) => {
          console.log('data', data);
          next(g.next(data));
        }).catch((err) => {
          console.error(err);
          next(g.throw(err));
        });
      }
  
      next(g.next());
    }
  
    generateAutoExec(genFun, taskArr);

Recommended Today

The real problem of Alibaba IOS algorithm can’t hang up this time

More and more IOS developers continue to enter the peak of job hopping in 2020 Three main trends of interview in 2020: IOS bottom layer, algorithm, data structure and audio and video development Occupied the main battlefield. Data structure and algorithm interview, especially figure, has become the main reason for the failure of most first-line […]