阐明
最近在温习 Promise 的常识,所以就做了一些题,这里挑出几道题,大家一起看看吧。
题目一
const promise = new Promise((resolve, reject) => { console.log(1); resolve(); console.log(2);})promise.then(() => { console.log(3);})console.log(4);
解析
首先 Promise 新建后立刻执行,所以会先输入 1,2,而 Promise.then()
外部的代码在 当次 事件循环的 结尾 立即执行 ,所以会持续输入4,最初输入3。
答案
1243
题目二
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);})
解析
resolve 函数
将 Promise 对象的状态从“未实现”变为“胜利”
(即从 pending 变为 resolved
),在异步操作胜利时调用,并将异步操作的后果,作为参数传递进来;
reject 函数
将 Promise 对象的状态从“未实现”变为“失败”
(即从 pending 变为 rejected
),在异步操作失败时调用,并将异步操作报出的谬误,作为参数传递进来。
而一旦状态扭转,就不会再变。
所以 代码中的reject('error');
不会有作用。
Promise 只能 resolve 一次,剩下的调用都会被疏忽。
所以 第二次的 resolve('success2');
也不会有作用。
答案
then: success1
题目三
Promise.resolve(1) .then(2) .then(Promise.resolve(3)) .then(console.log)
解析
Promise.resolve
办法的参数如果是一个原始值,或者是一个不具备 then
办法的对象,则 Promise.resolve
办法返回一个新的 Promise
对象,状态为resolved
,Promise.resolve
办法的参数,会同时传给回调函数。
then
办法承受的参数是函数,而如果传递的并非是一个函数,它实际上会将其解释为 then(null)
,这就会导致前一个 Promise
的后果会穿透上面。
答案
1
题目四
红灯三秒亮一次,绿灯一秒亮一次,黄灯2秒亮一次;如何让三个灯一直交替反复亮灯?(用Promse实现)三个亮灯函数曾经存在:参考 前端进阶面试题具体解答
function red() { console.log('red');}function green() { console.log('green');}function yellow() { console.log('yellow');}
解析
红灯三秒亮一次,绿灯一秒亮一次,黄灯2秒亮一次,意思就是3秒,执行一次 red 函数,2秒执行一次 green 函数,1秒执行一次 yellow 函数,一直交替反复亮灯,意思就是依照这个程序始终执行这3个函数,这步能够就利用递归来实现。
答案
function red() { console.log('red');}function green() { console.log('green');}function yellow() { console.log('yellow');}var light = function (timmer, cb) { return new Promise(function (resolve, reject) { setTimeout(function () { cb(); resolve(); }, timmer); });};var step = function () { Promise.resolve().then(function () { return light(3000, red); }).then(function () { return light(2000, green); }).then(function () { return light(1000, yellow); }).then(function () { step(); });}step();
题目五
实现 mergePromise 函数,把传进去的数组按程序先后执行,并且把返回的数据先后放到数组 data 中。
const timeout = ms => new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, ms);});const ajax1 = () => timeout(2000).then(() => { console.log('1'); return 1;});const ajax2 = () => timeout(1000).then(() => { console.log('2'); return 2;});const ajax3 = () => timeout(2000).then(() => { console.log('3'); return 3;});const mergePromise = ajaxArray => { // 在这里实现你的代码};mergePromise([ajax1, ajax2, ajax3]).then(data => { console.log('done'); console.log(data); // data 为 [1, 2, 3]});// 要求别离输入// 1// 2// 3// done// [1, 2, 3]
解析
首先 ajax1 、ajax2、ajax3
都是函数,只是这些函数执行后会返回一个 Promise
,按题目的要求咱们只有程序执行这三个函数就好了,而后把后果放到 data
中,然而这些函数里都是异步操作,想要按程序执行,而后输入 1,2,3并没有那么简略,看个例子。
function A() { setTimeout(function () { console.log('a'); }, 3000);}function B() { setTimeout(function () { console.log('b'); }, 1000);}A();B();// b// a
例子中咱们是按程序执行的 A
,B
然而输入的后果却是 b
,a
对于这些异步函数来说,并不会按程序执行完一个,再执行后一个。
这道题就是考用 Promise
管制异步流程,咱们要想方法,让这些函数,一个执行完之后,再执行下一个,看答案吧。
答案
// 保留数组中的函数执行后的后果var data = [];// Promise.resolve办法调用时不带参数,间接返回一个resolved状态的 Promise 对象。var sequence = Promise.resolve();ajaxArray.forEach(function (item) { // 第一次的 then 办法用来执行数组中的每个函数, // 第二次的 then 办法承受数组中的函数执行后返回的后果, // 并把后果增加到 data 中,而后把 data 返回。 // 这里对 sequence 的从新赋值,其实是相当于缩短了 Promise 链 sequence = sequence.then(item).then(function (res) { data.push(res); return data; });})// 遍历完结后,返回一个 Promise,也就是 sequence, 他的 [[PromiseValue]] 值就是 data,// 而 data(保留数组中的函数执行后的后果) 也会作为参数,传入下次调用的 then 办法中。return sequence;
题目六
以下代码最初输入什么?
const first = () => (new Promise((resolve, reject) => { console.log(3); let p = new Promise((resolve, reject) => { console.log(7); setTimeout(() => { console.log(5); resolve(6); }, 0) resolve(1); }); resolve(2); p.then((arg) => { console.log(arg); });}));first().then((arg) => { console.log(arg);});console.log(4);
解析
这道题就其实和 Promise
的关系不太大,次要是须要了解 JS执行机制,能力很好的解决这道题,对于 JS 执行机制不理解的敌人举荐看看这篇文章
这一次,彻底弄懂 JavaScript 执行机制
第一轮事件循环
先执行宏工作,主script ,new Promise立刻执行,输入【3】,
执行 p 这个new Promise 操作,输入【7】,
发现 setTimeout,将回调放入下一轮工作队列(Event Queue),p 的 then,权且叫做 then1,放入微工作队列,发现 first 的 then,叫 then2,放入微工作队列。执行console.log(4)
,输入【4】,宏工作执行完结。
再执行微工作,执行 then1,输入【1】,
执行 then2,输入【2】。
到此为止,第一轮事件循环完结。开始执行第二轮。
第二轮事件循环
先执行宏工作外面的,也就是 setTimeout 的回调,输入【5】。resolve(6)
不会失效,因为 p 这个 Promise 的状态一旦扭转就不会在扭转了。
答案
374125
题目七
有 8 个图片资源的 url,曾经存储在数组 urls
中(即urls = ['http://example.com/1.jpg', ...., 'http://example.com/8.jpg'])
,而且曾经有一个函数 function loadImg
,输出一个 url 链接,返回一个 Promise,该 Promise 在图片下载实现的时候 resolve,下载失败则 reject。
然而咱们要求,任意时刻,同时下载的链接数量不能够超过 3 个。
请写一段代码实现这个需要,要求尽可能疾速地将所有图片下载实现。
var urls = ['https://www.kkkk1000.com/images/getImgData/getImgDatadata.jpg', 'https://www.kkkk1000.com/images/getImgData/gray.gif', 'https://www.kkkk1000.com/images/getImgData/Particle.gif', 'https://www.kkkk1000.com/images/getImgData/arithmetic.png', 'https://www.kkkk1000.com/images/getImgData/arithmetic2.gif', 'https://www.kkkk1000.com/images/getImgData/getImgDataError.jpg', 'https://www.kkkk1000.com/images/getImgData/arithmetic.gif', 'https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/10/29/166be40ccc434be0~tplv-t2oaga2asx-image.image'];function loadImg(url) { return new Promise((resolve, reject) => { const img = new Image() img.onload = function () { console.log('一张图片加载实现'); resolve(); } img.onerror = reject img.src = url })};
解析
题目的意思是须要咱们这么做,先并发申请 3 张图片,当一张图片加载实现后,又会持续发动一张图片的申请,让并发数放弃在 3 个,直到须要加载的图片都全副发动申请。
用 Promise 来实现就是,先并发申请3个图片资源,这样能够失去 3 个 Promise,组成一个数组,就叫promises
吧,而后一直的调用 Promise.race 来返回最快扭转状态的 Promise,而后从数组(promises
)中删掉这个 Promise 对象,再退出一个新的 Promise,直到全副的 url 被取完,最初再应用 Promise.all 来解决一遍数组(promises
)中没有扭转状态的 Promise。
答案
var urls = ['https://www.kkkk1000.com/images/getImgData/getImgDatadata.jpg', 'https://www.kkkk1000.com/images/getImgData/gray.gif', 'https://www.kkkk1000.com/images/getImgData/Particle.gif', 'https://www.kkkk1000.com/images/getImgData/arithmetic.png', 'https://www.kkkk1000.com/images/getImgData/arithmetic2.gif', 'https://www.kkkk1000.com/images/getImgData/getImgDataError.jpg', 'https://www.kkkk1000.com/images/getImgData/arithmetic.gif', 'https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/10/29/166be40ccc434be0~tplv-t2oaga2asx-image.image'];function loadImg(url) { return new Promise((resolve, reject) => { const img = new Image() img.onload = function () { console.log('一张图片加载实现'); resolve(); } img.onerror = reject img.src = url })};function limitLoad(urls, handler, limit) { // 对数组做一个拷贝 const sequence = [].concat(urls) let promises = []; //并发申请到最大数 promises = sequence.splice(0, limit).map((url, index) => { // 这里返回的 index 是工作在 promises 的脚标,用于在 Promise.race 之后找到实现的工作脚标 return handler(url).then(() => { return index }); }); // 利用数组的 reduce 办法来以队列的模式执行 return sequence.reduce((last, url, currentIndex) => { return last.then(() => { // 返回最快扭转状态的 Promise return Promise.race(promises) }).catch(err => { // 这里的 catch 不仅用来捕捉 后面 then 办法抛出的谬误 // 更重要的是避免中断整个链式调用 console.error(err) }).then((res) => { // 用新的 Promise 替换掉最快扭转状态的 Promise promises[res] = handler(sequence[currentIndex]).then(() => { return res }); }) }, Promise.resolve()).then(() => { return Promise.all(promises) })}limitLoad(urls, loadImg, 3)/*因为 limitLoad 函数也返回一个 Promise,所以当 所有图片加载实现后,能够持续链式调用limitLoad(urls, loadImg, 3).then(() => { console.log('所有图片加载实现');}).catch(err => { console.error(err);})*/
总结
这几道题,有考查 Promise 基础知识的,也有考对 Promise 灵活运用的,如果这些题你都做的很好的话,那你对 Promise 的了解应该是不错的了。
最初,如果文中有有余或者谬误的中央,还请小伙伴们指出,万分感激。
如果感觉文章说的内容不够,最初有与题目相干的文章,能够看看。