面试题
1.你对回调地狱的理解?
2.如何解决回调地狱?
通过链式调用的方式打破回调地狱,增加代码的可读性
axios.get().then(res)=>{
return axios.post()
}.then()
3.event loop 浏览器事件循环机制 (关于同步异步代码的执行顺序)?
有同步先执行同步,异步里得看代码的异步层级
4.promise 是异步还是同步?
promise本身是同步 它的
.then和.catch方法是异步
5.宏任务和微任务的区别 分别有哪些?
同一层级先执行微任务,后执行宏任务
微任务目前接触的:promise的
.then和.catch方法
6.你对promise 的理解
promise本身是一个类 通过new进行调用 有三个状态
默认状态pending 等待
resolve=== fulfilled 成功
reject rejected 失败
状态永远只会改变一次 不可逆
异步转同步 --【简化代码】 async awiat
有个缺陷
-
通过promise使用的异步代码
new Promise((resolve,reject)=>{
resolve()
})
p.then()
p.catch()
-
通过async awiat
1.async必须写在函数的小括号前面
2.awiat 必须搭配async使用,写在异步代码前[作用:等待异步代码的结束,并返回成功执行的结果]
const fn = ()=>{
http.get('xxxx').then(res=>{
//res 后端返给前端的数据
}).catch(err=>{
//err 报错的数据
})
}
const fn = async ()=>{
let res = await http.get('xxxx');
//res 后端返给前端的数据
}
-
案例
http.get('/list')
.then(res => {
return http.post('/info', { id: res.data.id })
}).then(res1 => {
return http.post('/avatar', { id: res1.data.id, username: res1.data.username })
}).then(res2 => {
console.log(res2.data);
})
const getData = async ()=>{
let res = await http.get('/list');
let res1 = await http.post('/info', { id: res.data.id });
let res2 = await http.post('/avatar', { id: res1.data.id, username: res1.data.username })
let data = {...res.data,...res1.data,...res2.data}
console.log(data)
}
getData()
try catah 异常捕获
作用 :解决 await 报错 卡死的情况,并捕获错误信息 返回
const getData = async ()=>{
console.log(2);
//如果await 出现异常 导致 后面的代码 全部不执行 awiat 卡死
//等待异步代码的执行结束 返回异步代码的成功的值
let res = await axios.get('/xxxx')
console.log(3); //不执行
console.log(res); //不执行
}
getData()
const getData = async ()=>{
console.log(2);
//如果await 出现异常 导致 后面的代码 全部不执行 awiat 卡死
//等待异步代码的执行结束 返回异步代码的成功的值
try{
let res = await axios.get('/xxxx')
console.log(res);
}catch(err){
console.log(err);
alert(err.message)
}
//跟await 结果没有关系的代码放在trycatch 后面 照常执行
console.log(3);
}
getData()
promise内置方法
then 成功
catch 失败
finally //写不管成功 还是失败 都要执行的代码
//成功-->then 失败-->catch
//有一些代码 不管成功 还是失败 都要执行
let p = new Promise((resolve,reject)=>{
resolve()
}).then(res=>{
}).catch(err=>{
}).finally(_=>{
//写不管成功 还是失败 都要执行的代码
})
promise.all 内置方法
-
作用
将多个promise装到一起执行,都成功之后,一次性返回多个promise执行结果
-
使用场景
接口3 必须要 接口1 和 接口2拿到返回数据才可以调用
接口1 和 接口2 不区分先后顺序
需求:只要接口1和接口2成功后 就可以调用接口3
Promise.all([http.get('/list'),http.post('/info', { id: 1 })])
.then(res=>{
console.log(res);//[p1 的结果 p2的结果 p3的结果]
//调用第三个promise
http.post('/avatar', { id: 1, username: "3aaaac"}).then()
})
-
如果没有promise.all 方法 如何解决?
定义公共变量,默认值0,
接口1成功 +1
接口2成功 +1
不断地 定时器 判断变量==2 马上调用接口3 且 停止定时器
let num = 0;
http.get('/list').then(res=>{
num++
})
http.post('/info', { id: 1 }).then(res=>{
num++
})
let timer = setInterval(()=>{
if(num==2){
http.post('/avatar', { id: 1, username: "3aaaac"}).then(res=>{
console.log(res);
})
clearInterval(timer)
}
},1000)
Promise.race
同时执行多个promise,返回res 只有一个promise的结果,谁跑的快 就是谁的结果
场景:接口1 和接口2 谁先拿到 返回值 res就是用谁的值
Promise.race ([http.get('/list'),http.post('/info', { id: 1 })])
.then(res=>{
console.log(res);//谁快拿到的谁的then值
})
330

被折叠的 条评论
为什么被折叠?



