-
Notifications
You must be signed in to change notification settings - Fork 3.3k
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
第 129 题:输出以下代码执行结果 #251
Comments
理解任务队列(消息队列)一种是同步任务(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运行机制已经有个粗浅的认识了! // new Promise(xx)相当于同步任务, 会立即执行, .then后面的是微任务
console.log('----------------- start -----------------');
setTimeout(() => {
console.log('setTimeout');
}, 0)
new Promise((resolve, reject) =>{ // new Promise(xx)相当于同步任务, 会立即执行, .then后面的是微任务
for (var i = 0; i < 5; i++) {
console.log(i);
}
resolve();
}).then(() => {
console.log('promise实例成功回调执行');
})
console.log('----------------- end -----------------');
> ----------------- start -----------------
> 0
> 1
> 2
> 3
> 4
> ----------------- end -----------------
> promise实例成功回调执行
> setTimeout new Promise(xx)相当于同步任务, 会立即执行 所以: x,y,z 三个任务是几乎同时开始的, 最后的时间依然是10*1000ms (比这稍微大一点点, 超出部分在1x1000ms之内) |
三个任务发起的时候没有await,可以认为是同时发起了三个异步。之后各自await任务的结果。结果按最高耗时计算,由于三个耗时一样。所以结果是 10 * 1000ms |
执行wait方法是同步执行的,所以耗时是选最高的,x,y,z 的返回的结果await等于执行同步代码Promise.resolve(),await 的时候只执行同步代码 稍微改造一下就可以得到30 * 1000 ms以上的结果了 async function main () { main()` |
这是我见过最直接明白的异步同步解释 |
我认为肯定是大于10s的 |
function wait() {
return new Promise(resolve =>
setTimeout(resolve, 10 * 1000)
)
}
async function main() {
console.time();
const x = await wait(); // 每个都是都执行完才结,包括setTimeout(10*1000)的执行时间
const y = await wait(); // 执行顺序 x->y->z 同步执行,x 与 setTimeout 属于同步执行
const z = await wait();
console.timeEnd(); // default: 30099.47705078125ms
console.time();
const x1 = wait(); // x1,y1,z1 同时异步执行, 包括setTimeout(10*1000)的执行时间
const y1 = wait(); // x1 与 setTimeout 属于同步执行
const z1 = wait();
await x1;
await y1;
await z1;
console.timeEnd(); // default: 10000.67822265625ms
console.time();
const x2 = wait(); // x2,y2,z2 同步执行,但是不包括setTimeout(10*1000)的执行时间
const y2 = wait(); // x2 与 setTimeout 属于异步执行
const z2 = wait();
x2,y2,z2;
console.timeEnd(); // default: 0.065185546875ms
}
main(); |
示例2:将
|
不是并发,是同步执行 |
`async function test() {
先执行再等待,与直接执行并等待的区别吧 |
function wait() { async function main() { function wait() { async function main() { 建议对比理解,懂了吧? |
这算脑筋急转弯吗? |
输出以下代码执行结果
|
Promise.resolve() 你好 , 能帮忙写下这个例子的执行过程吗? 尤其是微任务队列的出入情况 |
The text was updated successfully, but these errors were encountered: