【建议星星】要就来45道Promise面试题一次爽到底(1.1w字用心整理)

前言

你盼世界,我盼望你无bug。Hello 你们好!我是霖呆呆!javascript

时隔一周不见,霖呆呆我终于更新文章了,小声嘀咕说想我了...html

呸...前端

咳咳,其实我一直在隐忍准备来一发大的好不。java

这不,这一章节就是整理了45Promise的笔试题让你们爽一爽 😁。es6

其实想要写一篇关于Promise的文章是由于以前在写别的文章的时候被评论区的一名读者无情的嘲讽了👎:面试

"做者的Promise必定很烂"ajax

因此编写这么一个主题霖呆呆我不是为了证实什么,而是想说:segmentfault

"说我烂我能够学啊"数组

另外查了不少关于Promise的面试题,有些一上来就很难的,有些连着几篇题目都是同样的,还有一些比较好的文章介绍的都是一些硬知识点。promise

这篇文章是一篇比较纯的Promise笔试文章,是我本身在作题的时候,根据题目想要的考点来反敲知识点,而后再由这个知识点编写从浅到深的的题目。

因此你能够看到题目中有一些基础题,而后再从基础题慢慢的变难,若是你看着感受这段位配不上你的话,请答应我坚持看下去,会愈来愈难的...

咳咳,按部就班嘛...

本文的题目没有到特别深刻,不过应该覆盖了大部分的考点,另外为了避免把你们绕混,答案也没有考虑在Node的执行结果,执行结果全为浏览器环境下。所以若是你都会作的话,能够尽情的在评论区再给我一个👎,放心,我脾气很好的...

OK👌, 来看看经过阅读本篇文章你能够学到:

  • Promise的几道基础题
  • Promise结合setTimeout
  • Promise中的then、catch、finally
  • Promise中的all和race
  • async/await的几道题
  • async处理错误
  • 综合题
  • 几道大厂的面试题

前期准备

在作下面👇的题目以前,我但愿你能清楚几个知识点。

(若是你感受一上来不想看这些列举的知识点的话,直接看后面的例子再来理解它们也能够)

event loop它的执行顺序:

  • 一开始整个脚本做为一个宏任务执行
  • 执行过程当中同步代码直接执行,宏任务进入宏任务队列,微任务进入微任务队列
  • 当前宏任务执行完出队,检查微任务列表,有则依次执行,直到所有执行完
  • 执行浏览器UI线程的渲染工做
  • 检查是否有Web Worker任务,有则执行
  • 执行完本轮的宏任务,回到2,依此循环,直到宏任务和微任务队列都为空

微任务包括:MutationObserverPromise.then()或reject()Promise为基础开发的其它技术,好比fetch APIV8的垃圾回收过程、Node独有的process.nextTick

宏任务包括scriptscriptsetTimeoutsetIntervalsetImmediateI/OUI rendering

注意⚠️:在全部任务开始的时候,因为宏任务中包括了script,因此浏览器会先执行一个宏任务,在这个过程当中你看到的延迟任务(例如setTimeout)将被放到下一轮宏任务中来执行。

1. Promise的几道基础题

1.1 题目一

const promise1 = new Promise((resolve, reject) => {
  console.log('promise1')
})
console.log('1', promise1);
复制代码

过程分析:

  • 从上至下,先遇到new Promise,执行该构造函数中的代码promise1
  • 而后执行同步代码1,此时promise1没有被resolve或者reject,所以状态仍是pending

结果:

'promise1'
'1' Promise{<pending>}
复制代码

1.2 题目二

const promise = new Promise((resolve, reject) => {
  console.log(1);
  resolve('success')
  console.log(2);
});
promise.then(() => {
  console.log(3);
});
console.log(4);
复制代码

过程分析:

  • 从上至下,先遇到new Promise,执行其中的同步代码1
  • 再遇到resolve('success'), 将promise的状态改成了resolved而且将值保存下来
  • 继续执行同步代码2
  • 跳出promise,往下执行,碰到promise.then这个微任务,将其加入微任务队列
  • 执行同步代码4
  • 本轮宏任务所有执行完毕,检查微任务队列,发现promise.then这个微任务且状态为resolved,执行它。

结果:

1 2 4 3
复制代码

1.3 题目三

const promise = new Promise((resolve, reject) => {
  console.log(1);
  console.log(2);
});
promise.then(() => {
  console.log(3);
});
console.log(4);
复制代码

过程分析

  • 和题目二类似,只不过在promise中并无resolve或者reject
  • 所以promise.then并不会执行,它只有在被改变了状态以后才会执行。

结果:

1 2 4
复制代码

1.4 题目四

const promise1 = new Promise((resolve, reject) => {
  console.log('promise1')
  resolve('resolve1')
})
const promise2 = promise1.then(res => {
  console.log(res)
})
console.log('1', promise1);
console.log('2', promise2);
复制代码

过程分析:

  • 从上至下,先遇到new Promise,执行该构造函数中的代码promise1
  • 碰到resolve函数, 将promise1的状态改变为resolved, 并将结果保存下来
  • 碰到promise1.then这个微任务,将它放入微任务队列
  • promise2是一个新的状态为pendingPromise
  • 执行同步代码1, 同时打印出promise1的状态是resolved
  • 执行同步代码2,同时打印出promise2的状态是pending
  • 宏任务执行完毕,查找微任务队列,发现promise1.then这个微任务且状态为resolved,执行它。

结果:

'promise1'
'1' Promise{<resolved>: 'resolve1'}
'2' Promise{<pending>}
'resolve1'
复制代码

1.5 题目五

接下来看看这道题:

const fn = () => (new Promise((resolve, reject) => {
  console.log(1);
  resolve('success')
}))
fn().then(res => {
  console.log(res)
})
console.log('start')
复制代码

这道题里最早执行的是'start'吗 🤔️ ?

请仔细看看哦,fn函数它是直接返回了一个new Promise的,并且fn函数的调用是在start以前,因此它里面的内容应该会先执行。

结果:

1
'start'
'success'
复制代码

1.6 题目六

若是把fn的调用放到start以后呢?

const fn = () =>
  new Promise((resolve, reject) => {
    console.log(1);
    resolve("success");
  });
console.log("start");
fn().then(res => {
  console.log(res);
});
复制代码

是的,如今start就在1以前打印出来了,由于fn函数是以后执行的。

注意⚠️:以前咱们很容易就觉得看到new Promise()就执行它的第一个参数函数了,其实这是不对的,就像这两道题中,咱们得注意它是否是被包裹在函数当中,若是是的话,只有在函数调用的时候才会执行。

答案:

"start"
1
"success"
复制代码

好嘞,学完了这几道基础题,让咱们来用个表情包压压惊。

2. Promise结合setTimeout

2.1 题目一

console.log('start')
setTimeout(() => {
  console.log('time')
})
Promise.resolve().then(() => {
  console.log('resolve')
})
console.log('end')
复制代码

过程分析:

  • 刚开始整个脚本做为一个宏任务来执行,对于同步代码直接压入执行栈进行执行,所以先打印出startend
  • setTimout做为一个宏任务被放入宏任务队列(下一个)
  • Promise.then做为一个微任务被放入微任务队列
  • 本次宏任务执行完,检查微任务,发现Promise.then,执行它
  • 接下来进入下一个宏任务,发现setTimeout,执行。

结果:

'start'
'end'
'resolve'
'time'
复制代码

2.2 题目二

const promise = new Promise((resolve, reject) => {
  console.log(1);
  setTimeout(() => {
    console.log("timerStart");
    resolve("success");
    console.log("timerEnd");
  }, 0);
  console.log(2);
});
promise.then((res) => {
  console.log(res);
});
console.log(4);
复制代码

过程分析:

和题目1.2很像,不过在resolve的外层加了一层setTimeout定时器。

  • 从上至下,先遇到new Promise,执行该构造函数中的代码1
  • 而后碰到了定时器,将这个定时器中的函数放到下一个宏任务的延迟队列中等待执行
  • 执行同步代码2
  • 跳出promise函数,遇到promise.then,但其状态仍是为pending,这里理解为先不执行
  • 执行同步代码4
  • 一轮循环事后,进入第二次宏任务,发现延迟队列中有setTimeout定时器,执行它
  • 首先执行timerStart,而后遇到了resolve,将promise的状态改成resolved且保存结果并将以前的promise.then推入微任务队列
  • 继续执行同步代码timerEnd
  • 宏任务所有执行完毕,查找微任务队列,发现promise.then这个微任务,执行它。

所以执行结果为:

1
2
4
"timerStart"
"timerEnd"
"success"
复制代码

2.3 题目三

题目三分了两个题目,由于看着都差很少,不过执行的结果却不同,你们不妨先猜猜下面两个题目分别执行什么:

(1):

setTimeout(() => {
  console.log('timer1');
  setTimeout(() => {
    console.log('timer3')
  }, 0)
}, 0)
setTimeout(() => {
  console.log('timer2')
}, 0)
console.log('start')
复制代码

(2):

setTimeout(() => {
  console.log('timer1');
  Promise.resolve().then(() => {
    console.log('promise')
  })
}, 0)
setTimeout(() => {
  console.log('timer2')
}, 0)
console.log('start')
复制代码

执行结果:

'start'
'timer1'
'timer2'
'timer3'
复制代码
'start'
'timer1'
'promise'
'timer2'
复制代码

这两个例子,看着好像只是把第一个定时器中的内容换了一下而已。

一个是为定时器timer3,一个是为Promise.then

可是若是是定时器timer3的话,它会在timer2后执行,而Promise.then倒是在timer2以前执行。

你能够这样理解,Promise.then是微任务,它会被加入到本轮中的微任务列表,而定时器timer3是宏任务,它会被加入到下一轮的宏任务中。

理解完这两个案例,能够来看看下面一道比较难的题目了。

2.3 题目三

Promise.resolve().then(() => {
  console.log('promise1');
  const timer2 = setTimeout(() => {
    console.log('timer2')
  }, 0)
});
const timer1 = setTimeout(() => {
  console.log('timer1')
  Promise.resolve().then(() => {
    console.log('promise2')
  })
}, 0)
console.log('start');
复制代码

这道题稍微的难一些,在promise中执行定时器,又在定时器中执行promise

而且要注意的是,这里的Promise是直接resolve的,而以前的new Promise不同。

所以过程分析为:

  • 刚开始整个脚本做为第一次宏任务来执行,咱们将它标记为宏1,从上至下执行
  • 遇到Promise.resolve().then这个微任务,将then中的内容加入第一次的微任务队列标记为微1
  • 遇到定时器timer1,将它加入下一次宏任务的延迟列表,标记为宏2,等待执行(先无论里面是什么内容)
  • 执行宏1中的同步代码start
  • 第一次宏任务(宏1)执行完毕,检查第一次的微任务队列(微1),发现有一个promise.then这个微任务须要执行
  • 执行打印出微1中同步代码promise1,而后发现定时器timer2,将它加入宏2的后面,标记为宏3
  • 第一次微任务队列(微1)执行完毕,执行第二次宏任务(宏2),首先执行同步代码timer1
  • 而后遇到了promise2这个微任务,将它加入这次循环的微任务队列,标记为微2
  • 宏2中没有同步代码可执行了,查找本次循环的微任务队列(微2),发现了promise2,执行它
  • 第二轮执行完毕,执行宏3,打印出timer2

因此结果为:

'start'
'promise1'
'timer1'
'promise2'
'timer2'
复制代码

若是感受有点绕的话,能够看下面这张图,就一目了然了。

2.4 题目四

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
  }, 1000)
})
const promise2 = promise1.then(() => {
  throw new Error('error!!!')
})
console.log('promise1', promise1)
console.log('promise2', promise2)
setTimeout(() => {
  console.log('promise1', promise1)
  console.log('promise2', promise2)
}, 2000)
复制代码

过程分析:

  • 从上至下,先执行第一个new Promise中的函数,碰到setTimeout将它加入下一个宏任务列表
  • 跳出new Promise,碰到promise1.then这个微任务,但其状态仍是为pending,这里理解为先不执行
  • promise2是一个新的状态为pendingPromise
  • 执行同步代码console.log('promise1'),且打印出的promise1的状态为pending
  • 执行同步代码console.log('promise2'),且打印出的promise2的状态为pending
  • 碰到第二个定时器,将其放入下一个宏任务列表
  • 第一轮宏任务执行结束,而且没有微任务须要执行,所以执行第二轮宏任务
  • 先执行第一个定时器里的内容,将promise1的状态改成resolved且保存结果并将以前的promise1.then推入微任务队列
  • 该定时器中没有其它的同步代码可执行,所以执行本轮的微任务队列,也就是promise1.then,它抛出了一个错误,且将promise2的状态设置为了rejected
  • 第一个定时器执行完毕,开始执行第二个定时器中的内容
  • 打印出'promise1',且此时promise1的状态为resolved
  • 打印出'promise2',且此时promise2的状态为rejected

完整的结果为:

'promise1' Promise{<pending>}
'promise2' Promise{<pending>}
test5.html:102 Uncaught (in promise) Error: error!!! at test.html:102
'promise1' Promise{<resolved>: "success"}
'promise2' Promise{<rejected>: Error: error!!!}
复制代码

2.5 题目五

若是你上面这道题搞懂了以后,咱们就能够来作作这道了,你应该能很快就给出答案:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("success");
    console.log("timer1");
  }, 1000);
  console.log("promise1里的内容");
});
const promise2 = promise1.then(() => {
  throw new Error("error!!!");
});
console.log("promise1", promise1);
console.log("promise2", promise2);
setTimeout(() => {
  console.log("timer2");
  console.log("promise1", promise1);
  console.log("promise2", promise2);
}, 2000);
复制代码

结果:

'promise1里的内容'
'promise1' Promise{<pending>}
'promise2' Promise{<pending>}
'timer1'
test5.html:102 Uncaught (in promise) Error: error!!! at test.html:102
'timer2'
'promise1' Promise{<resolved>: "success"}
'promise2' Promise{<rejected>: Error: error!!!}
复制代码

3. Promise中的then、catch、finally

额,可能你看到下面👇这么多的1,2,3脾气就上来了,不是说好了本篇文章没什么屁话嘛,怎么仍是这么多一二三四。

😂,你要理解个人用心良苦啊,我这是帮你把知识点都列举出来,作个总结而已。固然,你也能够先不看,先去作后面的题,而后再回过头来看这些,你就以为这些点都好好懂啊,甚至都不须要记。

总结:

  1. Promise的状态一经改变就不能再改变。(见3.1)
  2. .then.catch都会返回一个新的Promise。(上面的👆1.4证实了)
  3. catch无论被链接到哪里,都能捕获上层的错误。(见3.2)
  4. Promise中,返回任意一个非 promise 的值都会被包裹成 promise 对象,例如return 2会被包装为return Promise.resolve(2)
  5. Promise.then 或者 .catch 能够被调用屡次, 当若是Promise内部的状态一经改变,而且有了一个值,那么后续每次调用.then或者.catch的时候都会直接拿到该值。(见3.5)
  6. .then 或者 .catchreturn 一个 error 对象并不会抛出错误,因此不会被后续的 .catch 捕获。(见3.6)
  7. .then.catch 返回的值不能是 promise 自己,不然会形成死循环。(见3.7)
  8. .then 或者 .catch 的参数指望是函数,传入非函数则会发生值穿透。(见3.8)
  9. .then方法是能接收两个参数的,第一个是处理成功的函数,第二个是处理失败的函数,再某些时候你能够认为catch.then第二个参数的简便写法。(见3.9)
  10. .finally方法也是返回一个Promise,他在Promise结束的时候,不管结果为resolved仍是rejected,都会执行里面的回调函数。

3.1 题目一

const promise = new Promise((resolve, reject) => {
  resolve("success1");
  reject("error");
  resolve("success2");
});
promise
.then(res => {
    console.log("then: ", res);
  }).catch(err => {
    console.log("catch: ", err);
  })
复制代码

结果:

"then: success1"
复制代码

构造函数中的 resolvereject 只有第一次执行有效,屡次调用没有任何做用 。验证了第一个结论,Promise的状态一经改变就不能再改变。

3.2 题目二

const promise = new Promise((resolve, reject) => {
  reject("error");
  resolve("success2");
});
promise
.then(res => {
    console.log("then: ", res);
  }).then(res => {
    console.log("then: ", res);
  }).catch(err => {
    console.log("catch: ", err);
  }).then(res => {
    console.log("then: ", res);
  })
复制代码

结果:

"catch: " "error"
"then3: " undefined
复制代码

验证了第三个结论,catch无论被链接到哪里,都能捕获上层的错误。

3.3 题目三

Promise.resolve(1)
  .then(res => {
    console.log(res);
    return 2;
  })
  .catch(err => {
    return 3;
  })
  .then(res => {
    console.log(res);
  });
复制代码

结果:

1
2
复制代码

Promise能够链式调用,不过promise 每次调用 .then 或者 .catch 都会返回一个新的 promise,从而实现了链式调用, 它并不像通常咱们任务的链式调用同样return this

上面的输出结果之因此依次打印出12,那是由于resolve(1)以后走的是第一个then方法,并无走catch里,因此第二个then中的res获得的其实是第一个then的返回值。

return 2会被包装成resolve(2)

3.4 题目四

若是把3.3中的Promise.resolve(1)改成Promise.reject(1)又会怎么样呢?

Promise.reject(1)
  .then(res => {
    console.log(res);
    return 2;
  })
  .catch(err => {
    console.log(err);
    return 3
  })
  .then(res => {
    console.log(res);
  });
复制代码

结果:

1
3
复制代码

结果打印的固然是 1 和 3啦,由于reject(1)此时走的就是catch,且第二个then中的res获得的就是catch中的返回值。

3.5 题目五

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('timer')
    resolve('success')
  }, 1000)
})
const start = Date.now();
promise.then(res => {
  console.log(res, Date.now() - start)
})
promise.then(res => {
  console.log(res, Date.now() - start)
})
复制代码

执行结果:

'timer'
success 1001
success 1002
复制代码

固然,若是你足够快的话,也可能两个都是1001

Promise.then 或者 .catch 能够被调用屡次,但这里 Promise 构造函数只执行一次。或者说 promise 内部状态一经改变,而且有了一个值,那么后续每次调用 .then 或者 .catch 都会直接拿到该值。

3.6 题目六

Promise.resolve().then(() => {
  return new Error('error!!!')
}).then(res => {
  console.log("then: ", res)
}).catch(err => {
  console.log("catch: ", err)
})
复制代码

猜猜这里的结果输出的是什么 🤔️ ?

你可能想到的是进入.catch而后被捕获了错误。

结果并非这样的,它走的是.then里面:

"then: " "Error: error!!!"
复制代码

这也验证了第4点和第6点,返回任意一个非 promise 的值都会被包裹成 promise 对象,所以这里的return new Error('error!!!')也被包裹成了return Promise.resolve(new Error('error!!!'))

固然若是你抛出一个错误的话,能够用下面👇两的任意一种:

return Promise.reject(new Error('error!!!'));
// or
throw new Error('error!!!')
复制代码

3.7 题目七

const promise = Promise.resolve().then(() => {
  return promise;
})
promise.catch(console.err)
复制代码

.then.catch 返回的值不能是 promise 自己,不然会形成死循环。

所以结果会报错:

Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>
复制代码

3.8 题目八

Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .then(console.log)
复制代码

这道题看着好像很简单,又感受很复杂的样子,怎么这么多个.then啊... 😅

其实你只要记住原则8.then 或者 .catch 的参数指望是函数,传入非函数则会发生值穿透。

第一个then和第二个then中传入的都不是函数,一个是数字类型,一个是对象类型,所以发生了穿透,将resolve(1) 的值直接传到最后一个then里。

因此输出结果为:

1
复制代码

3.9 题目九

下面来介绍一下.then函数中的两个参数。

第一个参数是用来处理Promise成功的函数,第二个则是处理失败的函数。

也就是说Promise.resolve('1')的值会进入成功的函数,Promise.reject('2')的值会进入失败的函数。

让咱们来看看这个例子🌰:

Promise.reject('err!!!')
  .then((res) => {
    console.log('success', res)
  }, (err) => {
    console.log('error', err)
  }).catch(err => {
    console.log('catch', err)
  })
复制代码

这里的执行结果是:

'error' 'error!!!'
复制代码

它进入的是then()中的第二个参数里面,而若是把第二个参数去掉,就进入了catch()中:

Promise.reject('err!!!')
  .then((res) => {
    console.log('success', res)
  }).catch(err => {
    console.log('catch', err)
  })
复制代码

执行结果:

'catch' 'error!!!'
复制代码

可是有一个问题,若是是这个案例呢?

Promise.resolve()
  .then(function success (res) {
    throw new Error('error!!!')
  }, function fail1 (err) {
    console.log('fail1', err)
  }).catch(function fail2 (err) {
    console.log('fail2', err)
  })
复制代码

因为Promise调用的是resolve(),所以.then()执行的应该是success()函数,但是success()函数抛出的是一个错误,它会被后面的catch()给捕获到,而不是被fail1函数捕获。

所以执行结果为:

fail2 Error: error!!!
			at success
复制代码

3.10 题目十

接着来看看.finally(),这个功能通常不太用在面试中,不过若是碰到了你也应该知道该如何处理。

function promise1 () {
  let p = new Promise((resolve) => {
    console.log('promise1');
    resolve('1')
  })
  return p;
}
function promise2 () {
  return new Promise((resolve, reject) => {
    reject('error')
  })
}
promise1()
  .then(res => console.log(res))
  .catch(err => console.log(err))
  .finally(() => console.log('finally1'))

promise2()
  .then(res => console.log(res))
  .catch(err => console.log(err))
  .finally(() => console.log('finally2'))
复制代码

结果:

'promise1'
'1'
'error'
'finally1'
'finally2'
复制代码

4. Promise中的all和race

在作下面👇的题目以前,让咱们先来了解一下Promise.all()Promise.race()的用法。

通俗来讲,.all()的做用是接收一组异步任务,而后并行执行异步任务,而且在全部异步操做执行完后才执行回调。

.race()的做用也是接收一组异步任务,而后并行执行异步任务,只保留取第一个执行完成的异步操做的结果,其余的方法仍在执行,不过执行结果会被抛弃。

来看看题目一。

4.1 题目一

咱们知道若是直接在脚本文件中定义一个Promise,它构造函数的第一个参数是会当即执行的,就像这样:

const p1 = new Promise(r => console.log('当即打印'))
复制代码

控制台中会当即打印出 “当即打印”。

所以为了控制它何时执行,咱们能够用一个函数包裹着它,在须要它执行的时候,调用这个函数就能够了:

function runP1 () {
	const p1 = new Promise(r => console.log('当即打印'))
	return p1
}

runP1() // 调用此函数时才执行
复制代码

OK 👌, 让咱们回归正题。

如今来构建这么一个函数:

function runAsync (x) {
	const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
	return p
}
复制代码

该函数传入一个值x,而后间隔一秒后打印出这个x

若是我用.all()来执行它会怎样呢?

function runAsync (x) {
	const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
	return p
}
Promise.all([runAsync(1), runAsync(2), runAsync(3)])
  .then(res => console.log(res))
复制代码

先来想一想此段代码在浏览器中会如何执行?

没错,当你打开页面的时候,在间隔一秒后,控制台会同时打印出1, 2, 3,还有一个数组[1, 2, 3]

1
2
3
[1, 2, 3]
复制代码

因此你如今能理解这句话的意思了吗:有了all,你就能够并行执行多个异步操做,而且在一个回调中处理全部的返回数据。

.all()后面的.then()里的回调函数接收的就是全部异步操做的结果。

并且这个结果中数组的顺序和Promise.all()接收到的数组顺序一致!!!

有一个场景是很适合用这个的,一些游戏类的素材比较多的应用,打开网页时,预先加载须要用到的各类资源如图片、flash以及各类静态文件。全部的都加载完后,咱们再进行页面的初始化。

4.2 题目二

我新增了一个runReject函数,它用来在1000 * x秒后reject一个错误。

同时.catch()函数可以捕获到.all()里最早的那个异常,而且只执行一次。

想一想这道题会怎样执行呢 🤔️?

function runAsync (x) {
  const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
  return p
}
function runReject (x) {
  const p = new Promise((res, rej) => setTimeout(() => rej(`Error: ${x}`, console.log(x)), 1000 * x))
  return p
}
Promise.all([runAsync(1), runReject(4), runAsync(3), runReject(2)])
  .then(res => console.log(res))
  .catch(err => console.log(err))
复制代码

不卖关子了 😁,让我来公布答案:

1
3
// 2s后输出
2
Error: 2
// 4s后输出
4
复制代码

没错,就像我以前说的,.catch是会捕获最早的那个异常,在这道题目中最早的异常就是runReject(2)的结果。

另外,若是一组异步操做中有一个异常都不会进入.then()的第一个回调函数参数中。

注意,为何不说是不进入.then()中呢 🤔️?

哈哈,你们别忘了.then()方法的第二个参数也是能够捕获错误的:

Promise.all([runAsync(1), runReject(4), runAsync(3), runReject(2)])
  .then(res => console.log(res), 
  err => console.log(err))
复制代码

4.3 题目三

接下来让咱们看看另外一个有趣的方法.race

让我看看大家的英语水平如何?

快!一秒钟告诉我race是什么意思?

好吧...大家果真很强...

race,比赛,赛跑的意思。

因此使用.race()方法,它只会获取最早执行完成的那个结果,其它的异步任务虽然也会继续进行下去,不过race已经无论那些任务的结果了。

来,改造一下4.1这道题:

function runAsync (x) {
  const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
  return p
}
Promise.race([runAsync(1), runAsync(2), runAsync(3)])
  .then(res => console.log('result: ', res))
  .catch(err => console.log(err))
复制代码

执行结果为:

1
'result: ' 1
2
3
复制代码

这个race有什么用呢?使用场景仍是不少的,好比咱们能够用race给某个异步请求设置超时时间,而且在超时后执行相应的操做

4.4 题目四

改造一下题目4.2

function runAsync(x) {
  const p = new Promise(r =>
    setTimeout(() => r(x, console.log(x)), 1000)
  );
  return p;
}
function runReject(x) {
  const p = new Promise((res, rej) =>
    setTimeout(() => rej(`Error: ${x}`, console.log(x)), 1000 * x)
  );
  return p;
}
Promise.race([runReject(0), runAsync(1), runAsync(2), runAsync(3)])
  .then(res => console.log("result: ", res))
  .catch(err => console.log(err));
复制代码

遇到错误的话,也是同样的,在这道题中,runReject(0)最早执行完,因此进入了catch()中:

0
'Error: 0'
1
2
3
复制代码

总结

好的,让咱们来总结一下.then().race()吧,😄

  • Promise.all()的做用是接收一组异步任务,而后并行执行异步任务,而且在全部异步操做执行完后才执行回调。
  • .race()的做用也是接收一组异步任务,而后并行执行异步任务,只保留取第一个执行完成的异步操做的结果,其余的方法仍在执行,不过执行结果会被抛弃。
  • Promise.all().then()结果中数组的顺序和Promise.all()接收到的数组顺序一致。

5. async/await的几道题

既然谈到了Promise,那就确定得再说说async/await,在不少时候asyncPromise的解法差很少,又有些不同。不信你来看看题目一。

5.1 题目一

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}
async function async2() {
  console.log("async2");
}
async1();
console.log('start')
复制代码

这道基础题输出的是啥?

答案:

'async1 start'
'async2'
'start'
'async1 end'
复制代码

过程分析:

  • 首先一进来是建立了两个函数的,咱们先不看函数的建立位置,而是看它的调用位置
  • 发现async1函数被调用了,而后去看看调用的内容
  • 执行函数中的同步代码async1 start,以后碰到了await,它会阻塞async1后面代码的执行,所以会先去执行async2中的同步代码async2,而后跳出async1
  • 跳出async1函数后,执行同步代码start
  • 在一轮宏任务所有执行完以后,再来执行刚刚await后面的内容async1 end

(在这里,你能够理解为await后面的内容就至关于放到了Promise.then的里面)

来看看区别,若是咱们把await async2()换成一个new Promise呢?

async function async1() {
  console.log("async1 start");
  new Promise(resolve => {
    console.log('promise')
  })
  console.log("async1 end");
}
async1();
console.log("start")
复制代码

此时的执行结果为:

'async start'
'promise'
'async1 end'
'start'
复制代码

能够看到new Promise()并不会阻塞后面的同步代码async1 end的执行。

5.2 题目二

如今将async结合定时器看看。

给题目一中的 async2函数中加上一个定时器:

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}
async function async2() {
  setTimeout(() => {
    console.log('timer')
  }, 0)
  console.log("async2");
}
async1();
console.log("start")
复制代码

没错,定时器始终仍是最后执行的,它被放到下一条宏任务的延迟队列中。

答案:

'async1 start'
'async2'
'start'
'async1 end'
'timer'
复制代码

5.3 题目三

来吧,小伙伴们,让咱们多加几个定时器看看。😁

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
  setTimeout(() => {
    console.log('timer1')
  }, 0)
}
async function async2() {
  setTimeout(() => {
    console.log('timer2')
  }, 0)
  console.log("async2");
}
async1();
setTimeout(() => {
  console.log('timer3')
}, 0)
console.log("start")
复制代码

思考一下🤔,执行结果会是什么?

其实若是你能作到这里了,说明你前面的那些知识点也都掌握了,我就不须要太过详细的步骤分析了。

直接公布答案吧:

'async1 start'
'async2'
'start'
'async1 end'
'timer2'
'timer3'
'timer1'
复制代码

定时器谁先执行,你只须要关注谁先被调用的以及延迟时间是多少,这道题中延迟时间都是0,因此只要关注谁先被调用的。。

5.4 题目四

正常状况下,async中的await命令是一个Promise对象,返回该对象的结果。

但若是不是Promise对象的话,就会直接返回对应的值,至关于Promise.resolve()

async function fn () {
  // return await 1234
  // 等同于
  return 123
}
fn().then(res => console.log(res))
复制代码

结果:

123
复制代码

5.5 题目五

async function async1 () {
  console.log('async1 start');
  await new Promise(resolve => {
    console.log('promise1')
  })
  console.log('async1 success');
  return 'async1 end'
}
console.log('srcipt start')
async1().then(res => console.log(res))
console.log('srcipt end')
复制代码

这道题目比较有意思,你们要注意了。

async1await后面的Promise是没有返回值的,也就是它的状态始终是pending状态,所以至关于一直在awaitawaitawait却始终没有响应...

因此在await以后的内容是不会执行的,也包括async1后面的 .then

答案为:

'script start'
'async1 start'
'promise1'
'script end'
复制代码

5.6 题目六

让咱们给5.5中的Promise加上resolve

async function async1 () {
  console.log('async1 start');
  await new Promise(resolve => {
    console.log('promise1')
    resolve('promise1 resolve')
  }).then(res => console.log(res))
  console.log('async1 success');
  return 'async1 end'
}
console.log('srcipt start')
async1().then(res => console.log(res))
console.log('srcipt end')
复制代码

如今Promise有了返回值了,所以await后面的内容将会被执行:

'script start'
'async1 start'
'promise1'
'script end'
'promise1 resolve'
'async1 success'
'async1 end'
复制代码

5.7 题目七

async function async1 () {
  console.log('async1 start');
  await new Promise(resolve => {
    console.log('promise1')
    resolve('promise resolve')
  })
  console.log('async1 success');
  return 'async1 end'
}
console.log('srcipt start')
async1().then(res => {
  console.log(res)
})
new Promise(resolve => {
  console.log('promise2')
  setTimeout(() => {
    console.log('timer')
  })
})
复制代码

这道题应该也不难,不过有一点须要注意的,在async1中的new Promise它的resovle的值和async1().then()里的值是没有关系的,不少小伙伴可能看到resovle('promise resolve')就会误觉得是async1().then()中的返回值。

所以这里的执行结果为:

'script start'
'async1 start'
'promise1'
'promise2'
'async1 success'
'sync1 end'
'timer'
复制代码

5.8 题目八

咱们再来看一道头条曾经的面试题:

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}

async function async2() {
  console.log("async2");
}

console.log("script start");

setTimeout(function() {
  console.log("setTimeout");
}, 0);

async1();

new Promise(function(resolve) {
  console.log("promise1");
  resolve();
}).then(function() {
  console.log("promise2");
});
console.log('script end')
复制代码

有了上面👆几题作基础,相信你很快也能答上来了。

自信的写下大家的答案吧。

'script start'
'async1 start'
'async2'
'promise1'
'script end'
'async1 end'
'promise2'
'setTimeout'
复制代码

(这道题最后async1 endpromise2的顺序其实在网上饱受争议,我这里使用浏览器Chrome V80Node v12.16.1的执行结果都是上面这个答案)

5.9 题目九

好的👌,async/await大法已练成,我们继续:

async function testSometing() {
  console.log("执行testSometing");
  return "testSometing";
}

async function testAsync() {
  console.log("执行testAsync");
  return Promise.resolve("hello async");
}

async function test() {
  console.log("test start...");
  const v1 = await testSometing();
  console.log(v1);
  const v2 = await testAsync();
  console.log(v2);
  console.log(v1, v2);
}

test();

var promise = new Promise(resolve => {
  console.log("promise start...");
  resolve("promise");
});
promise.then(val => console.log(val));

console.log("test end...");
复制代码

答案:

'test start...'
'执行testSometing'
'promise start...'
'test end...'
'testSometing'
'执行testAsync'
'promise'
'hello async'
'testSometing' 'hello async'
复制代码

6. async处理错误

6.1 题目一

async中,若是 await后面的内容是一个异常或者错误的话,会怎样呢?

async function async1 () {
  await async2();
  console.log('async1');
  return 'async1 success'
}
async function async2 () {
  return new Promise((resolve, reject) => {
    console.log('async2')
    reject('error')
  })
}
async1().then(res => console.log(res))
复制代码

例如这道题中,await后面跟着的是一个状态为rejectedpromise

若是在async函数中抛出了错误,则终止错误结果,不会继续向下执行。

因此答案为:

'async2'
Uncaught (in promise) error
复制代码

若是改成throw new Error也是同样的:

async function async1 () {
  console.log('async1');
  throw new Error('error!!!')
  return 'async1 success'
}
async1().then(res => console.log(res))
复制代码

结果为:

'async1'
Uncaught (in promise) Error: error!!!
复制代码

6.2 题目二

若是想要使得错误的地方不影响async函数后续的执行的话,可使用try catch

async function async1 () {
  try {
    await Promise.reject('error!!!')
  } catch(e) {
    console.log(e)
  }
  console.log('async1');
  return Promise.resolve('async1 success')
}
async1().then(res => console.log(res))
console.log('script start')
复制代码

这里的结果为:

'script start'
'error!!!'
'async1'
'async1 success'
复制代码

或者你能够直接在Promise.reject后面跟着一个catch()方法:

async function async1 () {
  // try {
  // await Promise.reject('error!!!')
  // } catch(e) {
  // console.log(e)
  // }
  await Promise.reject('error!!!')
    .catch(e => console.log(e))
  console.log('async1');
  return Promise.resolve('async1 success')
}
async1().then(res => console.log(res))
console.log('script start')
复制代码

运行结果是同样的。

7. 综合题

上面👆的题目都是被我拆分着说一些功能点,如今让咱们来作一些比较难的综合题吧。

7.1 题目一

const first = () => (new Promise((resolve, reject) => {
    console.log(3);
    let p = new Promise((resolve, reject) => {
        console.log(7);
        setTimeout(() => {
            console.log(5);
            resolve(6);
          	console.log(p)
        }, 0)
        resolve(1);
    });
    resolve(2);
    p.then((arg) => {
        console.log(arg);
    });

}));

first().then((arg) => {
    console.log(arg);
});
console.log(4);
复制代码

过程分析:

  • 第一段代码定义的是一个函数,因此咱们得看看它是在哪执行的,发现它在4以前,因此能够来看看first函数里面的内容了。(这一步有点相似于题目1.5)
  • 函数first返回的是一个new Promise(),所以先执行里面的同步代码3
  • 接着又遇到了一个new Promise(),直接执行里面的同步代码7
  • 执行完7以后,在p中,遇到了一个定时器,先将它放到下一个宏任务队列里无论它,接着向下走
  • 碰到了resolve(1),这里就把p的状态改成了resolved,且返回值为1,不过这里也先不执行
  • 跳出p,碰到了resolve(2),这里的resolve(2),表示的是把first函数返回的那个Promise的状态改了,也先无论它。
  • 而后碰到了p.then,将它加入本次循环的微任务列表,等待执行
  • 跳出first函数,遇到了first().then(),将它加入本次循环的微任务列表(p.then的后面执行)
  • 而后执行同步代码4
  • 本轮的同步代码所有执行完毕,查找微任务列表,发现p.thenfirst().then(),依次执行,打印出1和2
  • 本轮任务执行完毕了,发现还有一个定时器没有跑完,接着执行这个定时器里的内容,执行同步代码5
  • 而后又遇到了一个resolve(6),它是放在p里的,可是p的状态在以前已经发生过改变了,所以这里就不会再改变,也就是说resolve(6)至关于没任何用处,所以打印出来的pPromise{<resolved>: 1}。(这一步相似于题目3.1)

结果:

3
7
4
1
2
5
Promise{<resolved>: 1}
复制代码

作对了的小伙伴奖励本身一朵小(大)(嘴)(巴)吧,😄

7.2 题目二

const async1 = async () => {
  console.log('async1');
  setTimeout(() => {
    console.log('timer1')
  }, 2000)
  await new Promise(resolve => {
    console.log('promise1')
  })
  console.log('async1 end')
  return 'async1 success'
} 
console.log('script start');
async1().then(res => console.log(res));
console.log('script end');
Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .catch(4)
  .then(res => console.log(res))
setTimeout(() => {
  console.log('timer2')
}, 1000)
复制代码

注意的知识点:

  • async函数中awaitnew Promise要是没有返回值的话则不执行后面的内容(相似题5.5)
  • .then函数中的参数期待的是函数,若是不是函数的话会发生穿透(相似题3.8 )
  • 注意定时器的延迟时间

所以本题答案为:

'script start'
'async1'
'promise1'
'script end'
1
'timer2'
'timer1'
复制代码

7.3 题目三

const p1 = new Promise((resolve) => {
  setTimeout(() => {
    resolve('resolve3');
    console.log('timer1')
  }, 0)
  resolve('resovle1');
  resolve('resolve2');
}).then(res => {
  console.log(res)
  setTimeout(() => {
    console.log(p1)
  }, 1000)
}).finally(res => {
  console.log('finally', res)
})
复制代码

注意的知识点:

  • Promise的状态一旦改变就没法改变(相似题目3.5)
  • finally无论Promise的状态是resolved仍是rejected都会执行,且它的回调函数是没有参数的(相似3.10)

答案:

'resolve1'
'finally' undefined
'timer1'
Promise{<resolved>: undefined}
复制代码

8. 几道大厂的面试题

8.1 使用Promise实现每隔1秒输出1,2,3

这道题比较简单的一种作法是能够用Promise配合着reduce不停的在promise后面叠加.then,请看下面的代码:

const arr = [1, 2, 3]
arr.reduce((p, x) => {
  return p.then(() => {
    return new Promise(r => {
      setTimeout(() => r(console.log(x)), 1000)
    })
  })
}, Promise.resolve())
复制代码

或者你能够更简单一点写:

const arr = [1, 2, 3]
arr.reduce((p, x) => p.then(() => new Promise(r => setTimeout(() => r(console.log(x)), 1000))), Promise.resolve())
复制代码

参考连接:如何让异步操做顺序执行

8.2 使用Promise实现红绿灯交替重复亮

红灯3秒亮一次,黄灯2秒亮一次,绿灯1秒亮一次;如何让三个灯不断交替重复亮灯?(用Promise实现)三个亮灯函数已经存在:

function red() {
    console.log('red');
}
function green() {
    console.log('green');
}
function yellow() {
    console.log('yellow');
}
复制代码

答案:

function red() {
  console.log("red");
}
function green() {
  console.log("green");
}
function yellow() {
  console.log("yellow");
}
const light = function (timer, cb) {
  return new Promise(resolve => {
    setTimeout(() => {
      cb()
      resolve()
    }, timer)
  })
}
const step = function () {
  Promise.resolve().then(() => {
    return light(3000, red)
  }).then(() => {
    return light(2000, green)
  }).then(() => {
    return light(1000, yellow)
  }).then(() => {
    return step()
  })
}

step();
复制代码

8.3 实现mergePromise函数

实现mergePromise函数,把传进去的数组按顺序前后执行,而且把返回的数据前后放到数组data中。

const time = (timer) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, timer)
  })
}
const ajax1 = () => time(2000).then(() => {
  console.log(1);
  return 1
})
const ajax2 = () => time(1000).then(() => {
  console.log(2);
  return 2
})
const ajax3 = () => time(1000).then(() => {
  console.log(3);
  return 3
})

function mergePromise () {
  // 在这里写代码
}

mergePromise([ajax1, ajax2, ajax3]).then(data => {
  console.log("done");
  console.log(data); // data 为 [1, 2, 3]
});

// 要求分别输出
// 1
// 2
// 3
// done
// [1, 2, 3]
复制代码

这道题有点相似于Promise.all(),不过.all()不须要管执行顺序,只须要并发执行就好了。可是这里须要等上一个执行完毕以后才能执行下一个。

解题思路:

  • 定义一个数组data用于保存全部异步操做的结果
  • 初始化一个const promise = Promise.resolve(),而后循环遍历数组,在promise后面添加执行ajax任务,同时要将添加的结果从新赋值到promise上。

答案:

function mergePromise (ajaxArray) {
  // 存放每一个ajax的结果
  const data = [];
  let promise = Promise.resolve();
  ajaxArray.forEach(ajax => {
  	// 第一次的then为了用来调用ajax
  	// 第二次的then是为了获取ajax的结果
    promise = promise.then(ajax).then(res => {
      data.push(res);
      return data; // 把每次的结果返回
    })
  })
  // 最后获得的promise它的值就是data
  return promise;
}
复制代码

8.4 根据promiseA+实现一个本身的promise

说真的,这道题被问到的几率仍是挺高的,并且要说的内容也不少...

霖呆呆这里偷个懒,不想细说了...

不过哈,我保证,下下题我必定仔细说 😼.

来吧,给大家一些好的宝典:

8.5 封装一个异步加载图片的方法

这个相对简单一些,只须要在图片的onload函数中,使用resolve返回一下就能够了。

来看看具体代码:

function loadImg(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = function() {
      console.log("一张图片加载完成");
      resolve(img);
    };
    img.onerror = function() {
    	reject(new Error('Could not load image at' + url));
    };
    img.src = url;
  });
复制代码

8.6 限制异步操做的并发个数并尽量快的完成所有

有8个图片资源的url,已经存储在数组urls中。

urls相似于['https://image1.png', 'https://image2.png', ....]

并且已经有一个函数function loadImg,输入一个url连接,返回一个Promise,该Promise在图片下载完成的时候resolve,下载失败则reject

但有一个要求,任什么时候刻同时下载的连接数量不能够超过3个

请写一段代码实现这个需求,要求尽量快速地将全部图片下载完成。

var urls = [
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting1.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting2.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting3.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting4.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting5.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn6.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn7.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn8.png",
];
function loadImg(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = function() {
      console.log("一张图片加载完成");
      resolve(img);
    };
    img.onerror = function() {
    	reject(new Error('Could not load image at' + url));
    };
    img.src = url;
  });
复制代码

看到这道题时,我最开始的想法是:

  • 拿到urls,而后将这个数组每3个url一组建立成一个二维数组
  • 而后用Promise.all()每次加载一组url(也就是并发3个),这一组加载完再加载下一组。

这个想法从技术上说并不难实现,有点相似于第三题。不过缺点也明显,那就是每次都要等到上一组所有加载完以后,才加载下一组,那若是上一组有2个已经加载完了,还有1个特别慢,还在加载,要等这个慢的也加载完才能进入下一组。这明显会照常卡顿,影响加载效率。

可是开始没有考虑这么多,所以有了第一个版本。

若是你有兴趣能够看看想法一的代码,虽然对你没什么帮助,想直接知道比较好的作法的小伙伴请跳到想法二

想法一💡:

function limitLoad (urls, handler, limit) {
  const data = []; // 存储全部的加载结果
  let p = Promise.resolve();
  const handleUrls = (urls) => { // 这个函数是为了生成3个url为一组的二维数组
    const doubleDim = [];
    const len = Math.ceil(urls.length / limit); // Math.ceil(8 / 3) = 3
    console.log(len) // 3, 表示二维数组的长度为3
    for (let i = 0; i < len; i++) {
      doubleDim.push(urls.slice(i * limit, (i + 1) * limit))
    }
    return doubleDim;
  }
  const ajaxImage = (urlCollect) => { // 将一组字符串url 转换为一个加载图片的数组
    console.log(urlCollect)
    return urlCollect.map(url => handler(url))
  }
  const doubleDim = handleUrls(urls); // 获得3个url为一组的二维数组
  doubleDim.forEach(urlCollect => {
    p = p.then(() => Promise.all(ajaxImage(urlCollect))).then(res => {
      data.push(...res); // 将每次的结果展开,并存储到data中 (res为:[img, img, img])
      return data;
    })
  })
  return p;
}
limitLoad(urls, loadImg, 3).then(res => {
  console.log(res); // 最终获得的是长度为8的img数组: [img, img, img, ...]
  res.forEach(img => {
    document.body.appendChild(img);
  })
});
复制代码

想法二💡:

参考LHH大翰仔仔-Promise面试题

既然题目的要求是保证每次并发请求的数量为3,那么咱们能够先请求urls中的前面三个(下标为0,1,2),而且请求的时候使用Promise.race()来同时请求,三个中有一个先完成了(例以下标为1的图片),咱们就把这个当前数组中已经完成的那一项(第1项)换成尚未请求的那一项(urls中下标为3)。

直到urls已经遍历完了,而后将最后三个没有完成的请求(也就是状态没有改变的Promise)用Promise.all()来加载它们。

很少说,流程图都给你画好了,你能够结合流程图再来看代码。

为了方便你查看,我截了个图,不过代码在后面也有

(说真的,要我看这一大长串代码我也不肯意...)

代码:

function limitLoad(urls, handler, limit) {
  let sequence = [].concat(urls); // 复制urls
  // 这一步是为了初始化 promises 这个"容器"
  let promises = sequence.splice(0, limit).map((url, index) => {
    return handler(url).then(() => {
      // 返回下标是为了知道数组中是哪一项最早完成
      return index;
    });
  });
  // 注意这里要将整个变量过程返回,这样获得的就是一个Promise,能够在外面链式调用
  return sequence
    .reduce((pCollect, url) => {
      return pCollect
        .then(() => {
          return Promise.race(promises); // 返回已经完成的下标
        })
        .then(fastestIndex => { // 获取到已经完成的下标
        	// 将"容器"内已经完成的那一项替换
          promises[fastestIndex] = handler(url).then(
            () => {
              return fastestIndex; // 要继续将这个下标返回,以便下一次变量
            }
          );
        })
        .catch(err => {
          console.error(err);
        });
    }, Promise.resolve()) // 初始化传入
    .then(() => { // 最后三个用.all来调用
      return Promise.all(promises);
    });
}
limitLoad(urls, loadImg, 3)
  .then(res => {
    console.log("图片所有加载完毕");
    console.log(res);
  })
  .catch(err => {
    console.error(err);
  });
复制代码

后语

知识无价,支持原创。

参考文章:

你盼世界, 我盼望你无bug。这篇文章就介绍到这里,一口气刷完了45道题,真的很爽有没有...

反正我作到后面是愈来愈有劲,也愈来愈自信了(有点飘,收一下...)

喜欢霖呆呆的小伙还但愿能够关注霖呆呆的公众号 LinDaiDai 或者扫一扫下面的二维码👇👇👇.

我会不定时的更新一些前端方面的知识内容以及本身的原创文章🎉

你的鼓励就是我持续创做的主要动力 😊.

相关推荐:

《全网最详bpmn.js教材》

《JavaScript进阶-执行上下文(理解执行上下文一篇就够了)》

《霖呆呆你来讲说浏览器缓存吧》

《建议改为: 读完这篇你还不懂Babel我给你寄口罩》

《怎样让后台小哥哥快速对接你的前端页面》