Realize the principle of

The principle is to split code fragments using generators. Then we use a function that iterates over itself, with each yield wrapped in a promise. The timing of the next step is controlled by the promise

implementation

function _asyncToGenerator(fn) { return function() { var self = this, args = arguments; Return new promise (function(resolve, reject) {var gen = fn.apply(self, args); Function _next(value) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value); } function _throw(err) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err); } // First trigger _next(undefined); }); }; }Copy the code
Perform iterative steps, Function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {try {var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) {// the iterator completes resolve(value); Resolve (1) a is a promise // const b = Resolve (a) b is a Promise. // If the Promise is finished, then the next function will be called recursively. Until done == true promise.resolve (value). Then (_next, _throw); }}Copy the code

The test method

const asyncFunc = _asyncToGenerator(function*() {
  const e = yield new Promise(resolve => {
    setTimeout(() => {
      resolve('e');
    }, 1000);
  });
  const a = yield Promise.resolve('a');
  const d = yield 'd';
  const b = yield Promise.resolve('b');
  const c = yield Promise.resolve('c');
  return [a, b, c, d, e];
});

asyncFunc().then(res => {
  console.log(res); // ['a', 'b', 'c', 'd', 'e']
});

Copy the code