joken-前端工程师

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

代码

class myPromise {
  constructor(syncFn) {
    this.callbacks = [];
	//resolve 的目的是调用下一个then中的函数
    const resolve = (value) => {
      const nextThenFn = this.callbacks.shift();
      if (nextThenFn) {
        nextThenFn(value);
      }
    };
	//第一个resolve 由异步自己唤起
    syncFn(resolve);
  }
  //then的目的是把then中的回调函数记录到队列数组中
  then(callback) {
    return new myPromise((resolve) => {
      this.callbacks.push((value) => {
        const nextValue = callback(value);
        resolve(nextValue);
      });
    });
  }
}


使用

const pr = new myPromise((resolve) => {
  setTimeout(() => {
    resolve("resolved");
  }, 1000);
});

pr.then((value) => {
  console.log(value, "svndslkdlsfjlksdjlfksj");
  return "sldfslkjfd";
}).then((value) => {
  console.log(value, "sldflkjfd");
});
posted on 2024-07-10 00:10  joken1310  阅读(1)  评论(0编辑  收藏  举报