本人有幸在《深入理解ES6》中看到如何通过自行封装生成器来执行异步任务,是它同步运行。
源码如下:

   function* queryInfo() {
        const res1 = yield new Promise((res, rej) => {
            res(200);
        });
        console.log({ res1 });
        try{
            const res2 = yield new Promise((res, rej) => {
                rej(403);
            });
            console.log({ res2 });
        }catch(e){
            console.log("res2错误:", e)
        }

        const res3 = yield new Promise((res, rej) => {
            res(304);
        });
        console.log({ res3 });
    }

    function run(gnFn) {
        // 创建迭代器
        const gn = gnFn();

        // 开启迭代
        let res = gn.next();

        const promiseRes = (function step() {
          if (!res.done) {
              const promise = Promise.resolve(res.value);

              return promise
              .then((value) => {
                res = gn.next(value);
                return step();
              })
              .catch((e) => {
                res = gn.throw(e);
                return step();
              });
          } else {
            return Promise.resolve(res.value);
          }
        })();

        return promiseRes;
    }

    run(queryInfo); // {res1: 200} res2错误:403 {res3: 304}


任天镗
12 声望2 粉丝