awit aync实现原理

function* g() {
  console.log("生成器开始");
  let data = yield fetchData();
  console.log("数据回来", data);
  let data2 = yield fetchData2(data);
  console.log(data2);
}
function fetchData() {
  var p = new Promise((res, rej) => {
    setTimeout(() => {
      res("我是数据");
    }, 1000);
  });
  return p;
}
function fetchData2(data) {
  var p = new Promise((res, rej) => {
    setTimeout(() => {
      res("我是数据2依赖于" + data);
    }, 1000);
  });
  return p;
}
// 执行器
function z(gen) {
  let g = gen();
  function next(d) {
    let tmp = g.next(d);
    if (tmp.done) return;
    tmp.value.then((data) => {
      next(data);
    });
  }
  next();
}
z(g);
promise手写+测试用例

const PENDING = "pending";
    const REJECTED = "rejected";
    const FULFILLED = "fulfilled";
    class myPromise {
      /* 
          fulfilled
          rejected
          pending
      */
      state = PENDING;
      result = void 0;
      tasks = [];
      nextPromiseState;
      constructor(fn) {
        if (typeof fn !== "function") {
          throw new TypeError(`Promise resolver ${fn} is not a function`);
        }
        try {
          fn(this.resolve.bind(this), this.reject.bind(this));
        } catch (error) {
          this.reject(error);
        }
      }
      resolve(data) {
        if (this.state !== PENDING) {
          return;
        }
        this.state = FULFILLED;
        this.handleTask(true);
        this.result = data;
        if (this.nextPromiseState) {
          this.nextPromiseState.res(this.result);
        }
      }
      reject(data) {
        if (this.state !== PENDING) {
          return;
        }
        this.state = REJECTED;
        this.handleTask(false);
        this.result = data;
        if (this.nextPromiseState) {
          this.nextPromiseState.rej(this.result);
        }
      }
      then(resFn, rejFn) {
        let resSelf;
        let rejSelf;
        const p = new myPromise((res, rej) => {
          resSelf = res;
          rejSelf = rej;
        });
        const task = {
          resFn,
          rejFn,
        };
        this.tasks.push(task);
        // 若为等待状态,则会把任务注册在当前promise的任务队列上
        if (this.state === PENDING) {
          this.nextPromiseState = {
            res: resSelf,
            rej: rejSelf,
          };
        }
        if (this.state === FULFILLED) {
          this.handleTask(true);
          resSelf(this.result);
        }

        if (this.state === REJECTED) {
          this.handleTask(false);
          rejSelf(this.result);
        }

        return p;
      }
      catch(fn) {
        this.then(null, fn);
      }
      // 处理任务队列的任务
      handleTask(res) {
        if (res) {
          while (this.tasks.length > 0) {
            const task = this.tasks.shift();
            if (task.resFn) {
              this.__setMiroTask(task.resFn);
            }
          }
        } else {
          while (this.tasks.length > 0) {
            const task = this.tasks.shift();
            if (task.rejFn) {
              this.__setMiroTask(task.rejFn);
            }
          }
        }
      }
      // 设置微任务函数
      __setMiroTask(fn) {
        // 判断MutationObserver是否存在
        if (typeof MutationObserver === "function") {
          const observer = new MutationObserver(() => {
            fn(this.result);
          });
          const text = document.createTextNode("2");
          observer.observe(text, { characterData: true });
          text.textContent = "1";
        } else {
          setTimeout(() => {
            fn(this.result);
          }, 0);
        }
      }
    }

    // new Promise(123); // Promise resolver 123 is not a function

    // test1
    // var s = new myPromise((res, rej) => {
    //   res(1);
    // }).then((res) => {
    //   console.log(res);
    // });
    // console.log(2);

    // test2
    // var s = new myPromise((res, rej) => {
    //   res(1);
    // })
    //   .then((res) => {
    //     console.log(res);
    //   })
    //   .then((res) => {
    //     console.log(res);
    //   });
    // console.log(2);

    // test3
    // var s = new myPromise((res, rej) => {
    //   rej(1);
    // })
    //   .then((res) => {
    //     console.log(res);
    //   })
    //   .then((res) => {
    //     console.log(res);
    //   })
    //   .catch((res) => {
    //     console.log(res);
    //   });
    // console.log(2);

    // test4
    // var s = new myPromise((res, rej) => {
    //   console.log(a);
    // })
    //   .then((res) => {
    //     console.log(res);
    //   })
    //   .catch((res) => {
    //     console.log("catch", res);
    //   });
    // console.log(2);

    // test5
    // var s = new myPromise((res, rej) => {
    //   setTimeout(() => {
    //     res(1);
    //   }, 1000);
    // })
    //   .then((res) => {
    //     console.log(res);
    //   })
    //   .then((res) => {
    //     console.log(res);
    //   })
    //   .catch((res) => {
    //     console.log("catch", res);
    //   });
    // console.log(2);

    // test6
    // async function main(params) {
    //   await new myPromise((res) => {
    //     setTimeout(() => {
    //       console.log(1);
    //       res(1);
    //     }, 1000);
    //   });
    //   console.log(2);
    // }
    // main();

    // test7
    // async function main(params) {
    //   try {
    //     await new myPromise((res, rej) => {
    //       setTimeout(() => {
    //         console.log(1);
    //         rej(123);
    //       }, 1000);
    //     });
    //     console.log(2);
    //   } catch (error) {
    //     console.log(222, error);
    //   }
    // }
    // main();
async function a(params) {
        await Promise.resolve(1)
    }
    async function test(params) {
        await a();
        console.log(1); 
    }
    
    async function main(params) {
        await test()
        console.log(2);
    }
    await后面跟async await的函数执行,需要等该函数执行完成后再把后续代码推入微队列。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值