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

第 26题(2019-08-26):输出以下代码执行结果 #28

Open
qappleh opened this issue Aug 26, 2019 · 1 comment
Open

第 26题(2019-08-26):输出以下代码执行结果 #28

qappleh opened this issue Aug 26, 2019 · 1 comment
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Aug 26, 2019

function wait() {
  return new Promise(resolve =>
  	setTimeout(resolve, 10 * 1000)
  )
}

async function main() {
  console.time();
  const x = wait();
  const y = wait();
  const z = wait();
  await x;
  await y;
  await z;
  console.timeEnd();
}
main();  
@qappleh
Copy link
Owner Author

qappleh commented Aug 27, 2019

理解任务队列(消息队列)
一种是同步任务(synchronous),另一种是异步任务(asynchronous)

 // 请问最后的输出结果是什么?
    console.log("A");
    while(true){ }
    console.log("B");

如果你的回答是A,恭喜你答对了,因为这是同步任务,程序由上到下执行,遇到while()死循环,下面语句就没办法执行。

// 请问最后的输出结果是什么?
    console.log("A");
    setTimeout(function(){
    	console.log("B");
    },0);
    while(true){}  

如果你的答案是A,恭喜你现在对js运行机制已经有个粗浅的认识了!
题目中的setTimeout()就是个异步任务。在所有同步任务执行完之前,任何的异步任务是不会执行的

所以: x,y,z 三个任务是几乎同时开始的, 最后的时间依然是10*1000ms (比这稍微大一点点, 超出部分在1x1000ms之内)

@qappleh qappleh added the js label Nov 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant