Open madfour opened 3 years ago
一种是同步任务(synchronous),另一种是异步任务(asynchronous)
// 请问最后的输出结果是什么?
console.log("A");
while(true){ }
console.log("B");
输出结果:A,因为这是同步任务,程序自上而下执行,遇到while()
死循环,下面语法无法执行
// 请问最后的输出结果是什么?
console.log("A");
setTimeout(function(){
console.log("B");
},0);
while(true){}
输出结果:A,
题目中的setTimeout()就是个异步任务。在所有同步任务执行完之前,任何的异步任务是不会执行的。
// 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)相当于同步任务, 会立即执行
new Promise
是一个同步运算,会立即执行。.then
里面的函数才是异步的(微任务)。所以相当于同时发起了三个异步任务。遇到
await
时,总时间就是三个任务中耗时最长的那个,即10*1000,所以总时间是10s多一点点。扩展: