我是靠谱客的博主 英勇导师,这篇文章主要介绍前端企业面试题:企业真实案例——33,现在分享给大家,希望可以做个参考。

手动实现一个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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function MyPromise(main){ let status = "pending"; //Promise对象状态 let tasklist = []; //保存所有的任务 let exceptionHander = null; function resolve(msg) { if(status == "pending") { status = "resovled"; //修改状态为resolved let next = tasklist.shift(); //从任务队列取出第一个 let newp = next(msg); //执行 if( newp instanceof MyPromise ) { //若有新的Promise出现 //将当前任务队列当中,剩余的任务,交接给下一个Promise tasklist.forEach( t=>{ newp.then( t ) }) } } } function reject(msg) { if( status == "pending") { //防止状态二次修改 status = "rejected"; exceptionHander ? exceptionHander(msg): throw new Error(msg); //执行异常处理 } } this.then = function( task ){ tasklist.push(task); //将任务存入队列当中 return this; } this.catch = function( fn ){ exceptionHander = fn; } this.getStatus = function(){ return status; } setTimeout(()=>{ main(resolve, reject); }, 0) }

Promise.all 实现

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
MyPromise.all = function(args){ let count = 0; let task = null; function resolve() { count++; if(count == args.length) task(); } args.forEach(p=>{ p.then(resolve); }) return { then( fn ){ task = fn; } } }

 

最后

以上就是英勇导师最近收集整理的关于前端企业面试题:企业真实案例——33的全部内容,更多相关前端企业面试题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部