美文网首页让前端飞
大厂面试Promise必备(上)

大厂面试Promise必备(上)

作者: Famous | 来源:发表于2022-04-06 10:05 被阅读0次

大厂经常会围绕Promise 来展开面试,我们就从面试角度反推,学好重要的知识点吧~

一、Promise 存在的原因和意义

有这样一个需求: 多个异步操作,要实现按照理想的顺序逐个执行,且能透传参数。这会带来回调地狱(多层嵌套)。在promise出现后,我们代码是这样的: P.then().then().then().then().then().... 优雅多了吧~

Tips: 让多个异步同步化,按序执行,解决了回调地域。

二、Promise 框架、Promise A+ 规范考点

Promise 有哪三种状态? -- pending(默认) fulfilled rejected 状态只能从p=>f 或者p=>r

new Promise 执行器executor()参数是什么? -- resolve、 reject

Promise value 保存成功状态的值有哪些? -- undefined / thenable / promise

Promise 保存失败状态? -- reason

Promise 一定会有then,then的参数? -- 两个回调onFulfilled(value) 、 onRejected(reason) (可用catch代替)

我要看原版全套!!! ===> 详细的promiseA+ 中文规范通道 英文规范通道

三、实现Promise (跟着敲吧,放心,一般敲到一半面试官就喊停了,,,)

1、手写一个简版Promise(5步搞定~)

// 第一步:  在类外部定义基本的promise 公共状态变量
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";
// 第二步: 把类的构造器和promise的两个基本方法then、catch定义好
class MyPromise{
  constructor(executor) { }
  then(onFulfilled, onRejected){ }
  catch(onRejected){ }
}
// 第三步: 构造器中定义promise status,成功,失败的值及成功失败的回调方法及回调数组及立即执行传入的函数
constructor(executor) {
    // 构造器 进来会立刻执行
    // 默认状态置为 PENDING
    this.status = PENDING;
    // 成功状态的值
    this.value = undefined;
    // 失败状态的值
    this.reason = undefined;
    // 存放成功的回调
    this.onResolvedCallbacks = [];
    // 存放失败的回调
    this.onRejectedCallbacks = [];
    // 成功状态的回调
    let resolve = (value) => {
      if (this.status === PENDING) {
        this.status = FULFILLED;
        this.value = value;
        this.onResolvedCallbacks.map((fn) => fn());
      }
    };
    // 失败状态的回调
    let reject = (reason) => {
      if (this.status === PENDING) {
        this.status = REJECTED;
        this.reason = reason;
        this.onRejectedCallbacks.map((fn) => fn());
      }
    };
    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }
// 第四步: 实现then,校验传入的参数,根据当前promise状态进行成功的回调和失败的回调,应包装成MyPromise,再return,可以实现链式调用。如果在pending就加入对应的事件队列,用push确保先入先出。
then(onFulfilled, onRejected) {
    // 没传参数时默认处理成函数
    onFulfilled =
      typeof onFulfilled === "function" ? onFulfilled : (value) => {};
    onRejected = typeof onRejected === "function" ? onRejected : (value) => {};
    if (this.status === FULFILLED) {
      return new MyPromise((resolve, reject) => {
        const value = onFulfilled(this.value);
        resolve(value);
      });
    } else if (this.status === REJECTED) {
      return new MyPromise((resolve, reject) => {
        onRejected(this.reason);
        reject(this.reason);
      });
    } else if (this.status === PENDING) {
      this.onResolvedCallbacks.push(() => {
        onFulfilled(this.value);
      });
      this.onRejectedCallbacks.push(() => {
        onRejected(this.reason);
      });
    }
  }
// 第五步: catch 只是then 的语法糖
 catch(onRejected) {
    return this.then(undefined, onRejected);
  }
验证一下
// 验证下我们的promise,成功和失败时的执行,以及then后连上catch(本质就是then的链式调用)
console.log("1");
const p = new MyPromise((resolve, reject) => {
  console.log("2");
  resolve("成功");
  // reject("失败");
  setTimeout(() => {
    console.log("4");
  }, 0);
})
  .then((res) => {
    console.log(res, "3");
  })
  .catch((res) => {
    console.log(res, "3");
  });

// 上述执行顺序为1,2,3,4
// 最后本质 ==>  js 处理异步核心   是转时间为空间

Tips: 上述顺序,可以简单记忆:HPT 宏任务->Promise->Time类函数 每个循环中按自上而下,先入先出

这个就涉及事件循环(event loop) 也是常考的内容,后面我们会结合考题来深入理解~

2、手写一个简版Promise.all

// 实现一个Promise all
// 不一定是数组,只要是可遍历的都要兼容,因此应使用for of
// 但是我们是为了面试时能写出来,那就越简单越好
const all = function (Promises) {
if (!Array.isArray(Promises)) {
  throw new Error("Promises must be an array");
}
return new MyPromise((resolve, reject) => {
  let Len = Promises.length;
  // 存放返回
  let resArr = [];
  Promises.map((pr, index) => {
    pr.then((res) => {
      resArr[index] = res;
      if (index == Len - 1) {
        resolve(resArr);
      }
    }).catch((res) => {
      // 有一个不满足立即退出
      reject(res);
    });
  });
});
};
验证一下all
// 测试
all([
  new MyPromise((resolve, reject) => {
    resolve(1);
  }),
  new MyPromise((resolve, reject) => {
    resolve(2);
    // reject("失败啦");
  }),
  new MyPromise((resolve, reject) => {
    resolve(3);
  }),
])
  .then((res) => console.log("result:", res))
  .catch((err) => {
    console.log("err:", err);
  });

3、手写一个简版Promise.race

会写all了,还要我写race? 简版都默认数组即可,复杂的兼容别的迭代类型

const race = function (Promises) {
  if (!Array.isArray(Promises)) {
    throw new Error("Promises must be an array");
  }
  return new Promise((resolve, reject) => {
    Promises.map((pr, index) => {
      pr.then((res) => {
        resolve(res);
        // 有一个满足立即退出
      }).catch((e) => {
        reject(e);
      });
    });
  });
};
验证一下race
// 测试
race([
  // 我们的MyPromise 还不支持setTimeOut 函数的等待,用Promise 来代替吧
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(3);
    }, 3000);
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(2);
      // reject(2);
    }, 2000);
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1);
    }, 1000);
  }),
])
  .then((res) => console.log("result:", res))
  .catch((err) => console.log(err));

后面我们再结合面试真题来搞懂H,P,T执行顺序吧~

相关文章

网友评论

    本文标题:大厂面试Promise必备(上)

    本文链接:https://www.haomeiwen.com/subject/avxzjrtx.html