You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
var r = new Promise(function(resolve, reject) {
console.log("a");
resolve();
});
setTimeout(() => console.log("d"), 0);
r.then(() => console.log("c"));
console.log("b");
// 执行顺序 a b c d
setTimeout(() => console.log("d"), 0);
var r1 = new Promise(function(resolve, reject) {
resolve();
});
r1.then(() => {
var begin = Date.now();
while (Date.now() - begin < 1000);
console.log("c1");
new Promise(function(resolve, reject) {
resolve();
}).then(() => console.log("c2"));
});
// 虽然第二个promise 间隔了1秒 但是还是 先于setTimeout执行
// c1 c2 d
function sleep(duration) {
return new Promise(function(resolve, reject) {
console.log("b");
setTimeout(resolve, duration);
});
}
console.log("a");
sleep(5000).then(() => console.log("c"));
// 将setTimeout封装成可以用于异步的函数
//a b c
概念
宏观任务:宿主发起的任务为宏观任务,如setTimeout、setInterval、setImmediate,I/O
微观任务:JavaScript引擎发起的任务为微观任务,如Promise
JavaScript引擎等待宿主环境分配宏观任务,宏观任务的队列可以理解为一个事件循环:
每个宏观任务中又包含一个微观任务队列有:
分析异步执行的方法
分析有多少个宏观任务
promise
async/await
async/await是ES7新特性,提供了用for if来编写异步代码的方式
async函数必定返回Promise,所有返回Promise的函数都可以认为是异步函数
async用来表示函数是异步的,定义的函数会返回一个promise对象,可以使用then方法添加回调函数。我们把所有返回 Promise 的函数都可以认为是异步函数。[所以它也是微观任务]
await 后面可以跟任何的JS 表达式。虽然说 await 可以等很多类型的东西,但是它最主要的意图是用来等待 Promise 对象的状态被 resolved。如果await的是 promise对象会造成异步函数停止执行并且等待 promise 的解决,如果等的是正常的表达式则立即执行。
async可以嵌套
The text was updated successfully, but these errors were encountered: