前端工程师面试涉及的知识点----ES6

一、谈一谈 promise

Promise是一种用于解决异步问题的思路、方案或者对象方式。在js中,经常使用异步的地方是Ajax交互。比如在es5时代,jQuery的ajax的使用success来完成异步的:

1
2
3
4
5
$.ajax({
url:'/xxx',
success:()=>{},
error: ()=>{}
})

但当存在多个回调函数时,可能会产生回调地狱。
ES6中的promise提供了一个then,来为异步提供回调函数:

1
2
3
4
5
6
7
$.ajax({
url:'/xxx',
}).then( ()=>{
// 成功的回调
}, ()=>{
// 失败的回调
})

一个具有多个回调的promise对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fn = new Promise(function (resolve, reject) {
let num = Math.ceil(Math.random() * 10)
if (num > 5) {
resolve(num)
} else {
reject(num)
}
})
// 第一次回调
fn.then((res)=>{
console.log(`res==>${res}`)
return new Promise((resolve,reject)=>{
if(2*res>15){
resolve(2*res)
}else{
reject(2*res)
}
})
},(err)=>{
console.log(`err==>${err}`)
}).then((res)=>{ // 第二次回调
console.log(res)
},(err)=>{
console.log(`err==>${err}`)
})

Promise的原理

  在Promise的内部,有一个状态管理器的存在,有三种状态:pending、fulfilled、rejected。

    (1) promise 对象初始化状态为 pending。

    (2) 当调用resolve(成功),会由pending => fulfilled。

    (3) 当调用reject(失败),会由pending => rejected。

  因此,看上面的的代码中的resolve(num)其实是将promise的状态由pending改为fulfilled,然后向then的成功回掉函数传值,reject反之。但是需要记住的是注意promsie状态 只能由 pending => fulfilled/rejected, 一旦修改就不能再变(记住,一定要记住,下面会考到)。

  当状态为fulfilled(rejected反之)时,then的成功回调函数会被调用,并接受上面传来的num,进而进行操作。promise.then方法每次调用,都返回一个新的promise对象 所以可以链式写法(无论resolve还是reject都是这样)。

Promise的几种方法

then

  then方法用于注册当状态变为fulfilled或者reject时的回调函数:

1
2
3
// onFulfilled 是用来接收promise成功的值
// onRejected 是用来接收promise失败的原因
promise.then(onFulfilled, onRejected);

  需要注意的地方是then方法是异步执行的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// resolve(成功) onFulfilled会被调用
const promise = new Promise((resolve, reject) => {
resolve('fulfilled'); // 状态由 pending => fulfilled
});
promise.then(result => { // onFulfilled
console.log(result); // 'fulfilled'
}, reason => { // onRejected 不会被调用
})

// reject(失败) onRejected会被调用
const promise = new Promise((resolve, reject) => {
reject('rejected'); // 状态由 pending => rejected
});
promise.then(result => { // onFulfilled 不会被调用
}, reason => { // onRejected
console.log(rejected); // 'rejected'
})
catch

  catch在链式写法中可以捕获前面then中发送的异常。

1
2
3
4
5
6
7
8
9
10
11
12
13
fn = new Promise(function (resolve, reject) {
let num = Math.ceil(Math.random() * 10)
if (num > 5) {
resolve(num)
} else {
reject(num)
}
})
fn..then((res)=>{
console.log(res)
}).catch((err)=>{
console.log(`err==>${err}`)
})

  其实,catch相当于then(null,onRejected),前者只是后者的语法糖而已。

嘤嘤嘤!!!
0%