Promise 是现在前端中非常常用的一个构造函数,因为他的产生解决了传统开发中回调地狱的问题,也正因为经常用,所以在面试中就经常被问到相关的面试题,今天抽空整理了下常见的Promise 相关的面试题。
一、对Promise executor执行时机的了解
面试官问: 下面这段代码会输出什么?
js
console.log(1);
const promise = new Promise((resolve, reject) => {
console.log(2);
resolve(3);
console.log(4);
});
console.log(5);
promise.then((res) => {
console.log(res);
});
console.log(6);
输出结果如下:

很多初学者可能会觉得输出结果是1,5,6,2,3,4 因为他们觉得Promise 是异步的,但其实不是这样的,Promise 的异步是then方法是异步的,而executor(传给Promise构造函数的函数) 是同步执行的。
二、错误处理
1. then 的第二个参数和catch执行优先级的问题
请说出下面的打印结果
js
const promise = new Promise((resolve, reject) => {
reject("出错了");
});
promise
.then(
(res) => {
console.log(res);
},
(err) => {
console.log("then 参数里面报出的错误:" + err);
}
)
.catch((err) => {
console.log("catch 参数里面报出的错误:" + err);
});
输出结果如下:

这其实主要考察你在学习的时候善不善于思考,和测试各种情况,这里在then的第二个参数函数中和catch都进行了错误处理,如果你之前已经测试过了,相信能不加思考就能写出答案。但是如果你学习的时候没有思考过这个问题,这个时候可能就只能靠猜了。
2. 错误处理的穿透性
请问下面的代码会打印什么?
js
const promise = new Promise((resolve, reject) => {
reject("出错了");
});
promise
.then((res) => {
console.log(res);
})
.then(
(res) => {},
(err) => {
console.log("第二个then:" + err);
}
);
输出结果如下:

有很多初学者可能会回答什么都不输出,或者说报错,他们的想法是executor 里面执行的reject ,而第一个then里面里面又没有第二个参数进行处理,所以不会输出任何东西,但现实不是这样的,Promise在处理错误时具有穿透性,第一个then 没有处理时,会到下一个then 进行处理,如果所有的then都没有第二个参数,且没有catch 才会报错。
三、多个then 如何进行结果传递
请问下面代码会输出什么结果?
js
const promise = new Promise((resolve, reject) => {
resolve("正确结果呀呀呀");
});
promise
.then((res) => {
console.log("第一个then:", res);
})
.then(
(res) => {
console.log("第二个then:" + res);
},
(err) => {
console.log("第二个then:" + err);
}
);
正确输出结果如下:

这里如果你回答错了面试官可能就不会再问了,如果你回答对了,面试官可能还会继续追问如何让第二个then 和第一个then输出同样的结果呢,第一种方式直接在第一个then 的第一个函数中return res 即可,代码修改如下:

第二种方式: 在第一个then 的第一个函数中return 一个 新的Promise ,代码修改如下

查看输出结果:

可以看到是我们想要的结果
今天就写到这里了,感谢收看,后续还会持续更新,欢迎收藏加关注