Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一个Promise面试题
 #7

Closed
lzlu opened this issue May 13, 2018 · 2 comments
Closed

一个Promise面试题
 #7

lzlu opened this issue May 13, 2018 · 2 comments

Comments

@lzlu
Copy link
Owner

lzlu commented May 13, 2018

原文地址: #7

本文没有什么干货,只是提供了一个面试题的解答思路。

这个题目是之前面试的时候遇到的,当时没答对。虽然这种题目看起来对写代码并没什么实际意义,但说到底还是自己对JS执行机制不够深入了解。

就拿这题目拿出来分享给大家一些解题思路。
对JS执行机制不够了解的建议先看了这篇这一次,彻底弄懂 JavaScript 执行机制 - 掘金,再食用。

不多说了,上酸菜,哦不对,题目。

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

}));

first().then((arg)=>{
    console.log(arg);
});
console.log(4);

第一轮事件循环

先执行宏任务,主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】。resovle不会生效,因为p这个Promise的状态一旦改变就不会在改变了。
所以最终的输出顺序是3、7、4、1、2、5。

总结

对JavaScript执行机制有了解,并且知道Promise构造函数是立即执行的,这个题目相信还是很简单的。

@Maopy
Copy link

Maopy commented May 14, 2018

应该叫 eventloop 面试题更贴切~

@lzlu
Copy link
Owner Author

lzlu commented Sep 27, 2018

@Maopy 确实

:octocat: From gitme iOS

@lzlu lzlu closed this as completed Sep 27, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants