代码
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");
});
    前端工程师、程序员

                
            
        
浙公网安备 33010602011771号