前端-promise、async 和 await-学习笔记
- 1 预备知识
- 2. Promise的理解和使用
- 3. Promise的API
- 1. Promise 构造函数:`Promise(executor) {}`
- 2. Promise.prototype.then 方法:`p.then(onResolved, onRejected)`
- 3. Promise.prototype.catch 方法:`p.catch(onRejected)`
- 4. Promise.resolve 方法:`Promise.resolve(value)`
- 5.Promise.reject 方法:`Promise.reject(reason)`
- 6. Promise.all 方法:`Promise.all(iterable)`
- 7. Promise.race方法:`Promise.race(iterable)`
- 4. Promise 的几个关键问题
- 5. Promise的优势
- 6. async 和 await的使用
- 7. 宏任务和微任务
1 预备知识
1.1 函数对象、实例对象
函数对象:将函数作为对象使用,简称函数对象
实例对象:new构造函数或类产生的对象,简称实例对象
function Person(nama,age){
this.name=name;
this.age=age;
}
# 将Person看成一个对象
Person.a=1
# p1是Person的实例对象
const p1=new Person('老刘',18)
1.2 两种类型的回调函数
什么是回调
我们定义的,我们没有调用,最终执行了
1.同步回调
理解:立即执行,完全执行完了才结束,不会放入回调队列中
例子:数组遍历相关的回调函数/Promisede executor函数
演示同步的回调函数:
let arr=[1,2,3,2,9]
arr.forEach((item)=>{
console.log(item)
})
console.log("主线程的代码")
2.异步回调
理解:不会立即执行,会放入回调队列中将来执行
例子:定时器回调 / ajax回调 / Promise成功或失败的回调
演示异步回调:
// 定时器回调
setTimeout(() => { // 异步回调,会放入队列中将来执行
console.log('@')
}, 0)
console.log('主线程的代码')
//主线程的代码 @
1.3 JS中的error
1.常见的错误类型
Error
:所有错误的父类型
ReferenceError
:引用的变量不存在
TypeError
:数据类型不正确
RangeError
:数据值不在其所允许的范围内(死循环)
SyntaxError
:语法错误
举例:
# ReferenceError:a is not defined引用的变量不存在
console.log(a)
#TypeError:Cannot read property 'xxx' of undefined数据类型不正确
let b
console.log(b.xxx)
# RangeError:Maximum call stack size exceeded数据值不在其所允许的范围内
const fn=() =>{ fn()}
fn()
#SyntaxError:Unexpected string语法错误
const c = """"
2.错误处理
捕获错误:
try ... catch
抛出错误:throw error
# 捕获处理异常
# 1.try中放可能出现的代码,一旦出现错误,立即停止try代码的执行,调用catch,并携带错误信息
try {
console.log(1)
console.log(a)
} catch (error) {
console.log("代码出错了,原因是",error);
}
# 抛出错误
function demo() {
if (Date.now()%2===1) {
console.log('当前时间为奇数,可以执行任务')
} else {
# 如果时间为偶数抛出异常(new Error错误对象),由调用来处理
throw new Error('当前时间为偶数,无法执行任务')
}
}
# 捕获处理异常
try {
demo()
} catch (error) {
console.log("代码出错了,原因是",error);
}
3. 错误对象
massage
属性:错误相关信息
stack
属性:函数调用栈记录信息
try {
let d
console.log(d.xxx)
} catch (error) {
console.log(error.message)// Cannot read property 'xxx' of undefined
console.log(error.stack)// TypeError:Cannot read property 'xxx' of undefined
}
2. Promise的理解和使用
2.1 Promise是什么
1 理解Promise
1.抽象表达:
①Promise
是一门新的技术(ES6提出)
②Promise
是JS中进行异步编程的新的解决方案(旧方案是单纯使用回调函数)
2.具体表达:
①从语法上看:
Promise
是一个构造函数 (自己身上有all
、reject
、resolve
这几个方法,原型上有then
、catch
等方法)
②从功能上看:promise
的实例对象用来封装一个异步操作并可以获取其成功/失败的结果值
注意:
1.Promise
不是回调,是一个内置的对象,程序员自己用new调用
2.new Promise的时候,要传入一个回调函数,它是同步的回调,会立即在主线程上执行,它被称为executor
函数
3.每个Promise
实例对象都有3个状态,分别为:初始化(pending
)、成功(fulfilled
)、失败(rejected
)
4.每一个Promise
实例在刚被new出来的那一刻,状态都是初始化(pending
)
5.executor函数会收到两个参数,它们都是函数,分别用形参:resolve、reject
接收
(1)调用resolve,会让Promise实例状态变为:成功(fulfilled),同时可以指定成功的value
(2)调用reject,会让Promise实例状态变为:失败(rejected),同时可以指定失败的reason
const promise = new Promise(function(resolve, reject) {
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(reason);
}
});
2 Promise的基本使用
2.1重要语法
new Promise(executor)构造函数
Promise.prototype.then方法
2.2基本编码流程
- 创建Promise的实例对象(pending状态),传入executor函数
- 在executor中启动异步任务(定时器、ajax请求)
- 根据异步任务的结果,做不同处理:
3.1如果异步任务成功了:
我们调用resolve(value),让Promise实例对象状态变成成功(fulfilled),同时可以指定成功的value
3.2如果异步任务失败了:
我们调用reject(reason),会让Promise实例状态变为:失败(rejected),同时可以指定失败的reason
4.通过then方法为promise的实例指定成功、失败的回调函数,来获取成功的value、失败的reason
注意:then方法所指定的:成功的回调、失败的回调,都是异步的回调
2.3.关于状态的注意点
3.1 三个状态
pending
:未确定的–初始状态
fulfilled
:成功的—调用resolve()后的状态
rejected
:失败的—调用reject()后的状态
3.2两种状态改变
pending==>fulfilled
pending==>rejected
3.3 状态只能改变一次
3.4一个promise指定多个成功/失败回调函数,都会调用’(多个then都会调用)
const p = new Promise(function(resolve, reject) {
// 执行异步操作任务
setTimeout(() => {
resolve('我是服务器返回的数据')
}, 2000);
})
p.then(
value => { console.log('成功的回调', value) }, //成功的回调-异步
reason => { console.log('失败的回调', reason)} //失败的回调-异步
)
console.log('@')
// @ 成功的回调 我是服务器返回的数据
3. Promise例子
const p = new Promise(function(resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response); //成功了,输出响应体
} else {
reject('请求出错',xhr.status); //失败了,输出响应状态码
}
}
}
xhr.open('GET', "http://poetry.apiopen.top/sentences");
xhr.responseTypr='json
xhr.send();
})
p.then(
value => { console.log('成功的回调', value) }, //成功的回调-异步
reason => { console.log('失败的回调', reason)} //失败的回调-异步
)
console.log('@')
// @ 成功的回调 我是服务器返回的数据
3.1 封装一个简单的ajax
定义一个sendAjax函数,对xhr的get请求进行封装
1.该函数接收两个参数:url(请求地址)、data(参数对象)
2.该函数返回一个Promise实例
(1)若ajax请求成功,则Promise实例成功,成功的value是返回的数据
(2)若ajax请求失败,则Promise实例失败,失败的reason是错误提示
function sendAjax(url,data){
return new Promise(function(resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.response);
else reject('请求出错',xhr.status);
}
}
# 整理参数
let str=''
for(let key in data){
str+=`${key}=${data[key]}&`
}
str.slice(0,-1)
xhr.open('GET', url+'?'+str);
xhr.responseTypr='json
xhr.send();
})
})
const x=sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'})
x.then(
value => { console.log('成功的回调', value) }, //成功的回调-异步
reason => { console.log('失败的回调', reason)} //失败的回调-异步
)
console.log('@')
// @ 成功的回调 我是服务器返回的数据
3.2封装一个简单的ajax(纯回调)
定义一个sendAjax函数,对xhr的get请求进行封装
1.该函数接收两个参数:url(请求地址)、data(参数对象)、success(成功的回调)error(失败的回调)
2.该函数没有返回值
function sendAjax(url,data,success,error){
return new Promise(function(resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) success(xhr.response);
else error('请求出错',xhr.status);
}
}
# 整理参数
let str=''
for(let key in data){
str+=`${key}=${data[key]}&`
}
str.slice(0,-1)
xhr.open('GET', url+'?'+str);
xhr.responseTypr='json
xhr.send();
})
})
const x=sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'})
x.then(
response => { console.log('成功了', response) }, //成功的回调-异步
err => { console.log('失败了',err)} //失败的回调-异步
)
3. Promise的API
1. Promise 构造函数:Promise(executor) {}
executor
函数:同步执行 (resolve, reject) => {}
resolve
函数:内部定义成功时调用的函数 resove(value)
reject
函数:内部定义失败时调用的函数 reject(reason)
说明:executor 是执行器,会在 Promise 内部立即同步回调,异步操作 resolve/reject 就在 executor 中执行
2. Promise.prototype.then 方法:p.then(onResolved, onRejected)
指定两个回调(成功+失败)
onFulfilled
函数:成功的回调函数 (value) => {}
onRejected
函数:失败的回调函数 (reason) => {}
特别注意(难点):指定用于得到成功 value 的成功回调和用于得到失败 reason 的失败回调,返回一个新的 promise 对象
# 验证.then方法返回一个新的 promise 对象
const p = new Promise(function(resolve, reject) {
// 执行异步操作任务
setTimeout(() => {
resolve('我是服务器返回的数据')
}, 2000);
})
const x =p.then(
value => { console.log('成功的回调', value) }, //成功的回调-异步
reason => { console.log('失败的回调', reason)} //失败的回调-异步
)
console.log('50',x,x===p) //不是p
3. Promise.prototype.catch 方法:p.catch(onRejected)
onRejected 函数:失败的回调函数 (reason) => {}
说明:这是then() 的语法糖,相当于 then(undefined, onRejected)
const p=new Promise((resolve, reject) => { // excutor执行器函数
setTimeout(() => {
reject('失败的数据') //reject()函数
}, 1000)
})
p.then(
undefined,
eason=> { console.log('失败了1',reason) }
)
p.catch(
reason => { // onRejected()函数
console.log('失败了2',reason) // 失败的数据
}
)
//失败了1 失败了2
4. Promise.resolve 方法:Promise.resolve(value)
说明:用于快速返回一个状态为fulfilled或rejected的Promise实例对象
备注:传入值可能为:(1)非Promise类型、(2)Promise 对象
如果Promise对象是失败的,返回就失败的
let p1 = Promise.reject(521);//如果传入的参数为 非Promise类型的对象, 则返回的结果为成功promise对象
let p2 = Promise.resolve(p1);//如果传入的参数为 Promise 对象, 则参数的结果决定了 resolve 的结果
p.then(
value => { console.log('成功的回调', value) }, //成功的回调-异步
reason => { console.log('失败的回调', reason)} //失败的回调-异步
)
5.Promise.reject 方法:Promise.reject(reason)
说明:用于快速返回一个状态必为rejected的Promise实例对象
let p1 = Promise.resolve(521);//如果传入的参数为 非Promise类型的对象, 则返回的结果为成功promise对象
let p2 = Promise.reject(p1);//如果传入的参数为 Promise 对象, 则参数的结果决定了 resolve 的结果
p.then(
value => { console.log('成功的回调', value) }, //成功的回调-异步
reason => { console.log('失败的回调', reason)} //失败的回调-异步
)
6. Promise.all 方法:Promise.all(iterable)
promiseArr:包含n个Promise实例的数组
说明:返回一个 新的 promise实例,只有所有promise都成功才成功,只要一个失败了就直接失败
# Promise.all
const p1 = Promise.resolve('a');
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('b');
},500)
})
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('b');
},2000)
})
const result = Promise.all([p1, p2, p3]);
console.log(result);
result.then(
value => { console.log('成功了', value) },
reason => { console.log('失败了', reason)}
)
//"成功了"["a", "b", "b"]
//失败了 "b" b失败就返回b,不在去等c了,500毫秒就返回
7. Promise.race方法:Promise.race(iterable)
promiseArr:包含n个promise实例的数组
说明:返回一个新的Promise实例,成功还是失败?以最先出结果的promise为准
# Promise.all
const p1 = Promise.resolve('a');
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('b');
},500)
})
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('b');
},2000)
})
const result = Promise.race([p1, p2, p3]);
console.log(result);
result.then(
value => { console.log('成功了', value)},
reason => { console.log('失败了', reason)}
)
//成功了 a
4. Promise 的几个关键问题
4.1 如何改变 promise 的状态?
(1)
resolve(value)
:如果当前是 pending 就会变为 resolved
(2)reject(reason):
如果当前是 pending 就会变为 rejected
(3)执行器(executor)抛出异常
:如果当前是 pending 就会变为 rejected
const p = new Promise((resolve, reject) => {
onsole.log('1')// 引擎抛异常
throw 999 // 编码抛异常
console.log('1')
})
p.then(
value => { console.log('成功了', value)},
reason => { console.log('失败了', reason)}
)
# "1""失败了"999
4.2改变 promise 状态和指定回调函数谁先谁后?
1.都有可能,常规是先指定回调再改变状态,但也可以先改状态再指定回调
2.如何先改变状态再指定回调?
延迟一会再调用then()
# 先改变状态,再指定回调
let p = new Promise((resolve, reject) => {
resolve('OK');
});
setTimeout(() => {// 直接拿出来执行了,来不及缓存了
p.then(
value =>{console.log(value);},
reason=>{console.log(reason);}
)
}, 1000);
3.什么时候才能得到数据?
(1)如果先指定的回调,那当状态发生改变时,回调函数就会调用得到数据
(2)如果先改变的状态,那当指定回调时,回调函数就会调用得到数据
4.3promise.then() 返回的【新 promise 实例】,它的值和状态由什么决定?
(1)简单表达:由 then() 指定的回调函数执行的结果决定
(2)详细表达:
①如果then所指定的回调返回的是非 promise 的值a:
【新 promise实例
】状态:成功(fulfilled),value 为值 a
② 如果then所指定的回调返回的是另一个新 promise实例p:
【新 promise实例
】的状态、值都会与新 promise 实例p一致
③ 如果then所定的回调抛出异常:
【新 promise实例
】状态 rejected,reason 为抛出的那个异常
如果返回的是非 promise 的任意值,新 promise 变为 resolved,value 为返回的值
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('a');
},1000)
})
const x=p.then(
value => { console.log('成功了1', value) return 900},
reason => { console.log('失败了1', reason)}
)
x.then(
value => { console.log('成功了2', value)},
reason => { console.log('失败了2', reason)}
)
//"成功了1""a""成功了2" 900
如果返回的是另一个新 promise,此 promise 的结果就会成为新 promise 的结果
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('a');
},1000)
})
const x=p.then(
value => { console.log('成功了1', value)
return Promise.reject('a'); //返回的是另一个新 promise
},
reason => { console.log('失败了1', reason)}
)
x.then(
value => { console.log('成功了2', value)},
reason => { console.log('失败了2', reason)}
)
/"成功了1" "a" "失败了2" "a"
const p = new Promise((resolve, reject) => {
setTimeout(() => {
reject('a');
},1000)
})
const x=p.then(
value => { console.log('成功了1', value) return 900},
reason => { console.log('失败了1', reason)} //返回undefined是非promise值
)
x.then(
value => { console.log('成功了2', value)},
reason => { console.log('失败了2', reason)}
)
//"失败了1" "a" "成功了2" undefined
练习
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('a');
},1000)
})
p.then(
value => { console.log('成功了1', value); return Promise.reject('a');}, //1.
reason => { console.log('失败了1', reason)} //返回undefined是非promise值
).then(
value => { console.log('成功了2', value); return true;},
reason => { console.log('失败了2', reason); return 100;} //2 返回a
).then(
value => { console.log('成功了3', value); throw 900 }, //3 返回100
reason => { console.log('失败了3', reason); return false;}
).then(
value => { console.log('成功了4', value); return -100;},
reason => { console.log('失败了4', reason);} //4. 返回900
)
"成功了1" "a"
"失败了2" "a"
"成功了3" 100
"失败了4" 900
4.4 纯回调的问题=>回调地狱
第一次请求成了发第二次,一共发三次请求
return new Promise(function(resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) success(xhr.response);
else error('请求出错',xhr.status);
}
}
# 整理参数
let str=''
for(let key in data){
str+=`${key}=${data[key]}&`
}
str.slice(0,-1)
xhr.open('GET', url+'?'+str);
xhr.responseTypr='json
xhr.send();
})
})
sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'},
response => {
console.log('第1次成功了', response);
sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'},
response => {
console.log('第2次成功了', response);
sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'},
response => {
console.log('第3次成功了', response);
},
err => { console.log('第3次失败了',err)}
)
},
err => { console.log('第2次失败了',err)}
)
},
err => { console.log('第1次失败了',err)}
)
4.5 promise 如何串联多个操作任务?
使用then 链式解决回调地狱
function sendAjax(url,data){
return new Promise(function(resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.response);
else reject('请求出错',xhr.status);
}
}
# 整理参数
let str=''
for(let key in data){
str+=`${key}=${data[key]}&`
}
str.slice(0,-1)
xhr.open('GET', url+'?'+str);
xhr.responseTypr='json
xhr.send();
})
})
sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'})
.then(
value => {
console.log('第1次请求成功了', value )
return sendAjax('http://api.apiopen.top/getJoke'{page:1,count:2,type:'video'})
},
reason => { console.log('第1次请求失败了', reason)}
)
.then(
value => {
console.log('第2次请求成功了', value )
return sendAjax('http://api.apiopen.top/getJoke'{page:1,count:2,type:'video'})
},
reason => { console.log('第2次请求失败了', reason)}
)
.then(
value => { console.log('第3次请求成功了', value ) },
reason => { console.log('第3次请求失败了', reason)}
)
4.6中断 promise 链?
中断 promise 链?
(1)当使用 promise 的 then 链式调用时,在中间中断,不再调用后面的回调函数
(2)办法:在回调函数中返回一个 pending 状态的 promise 对象
sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'})
.then(
value => {
console.log('第1次请求成功了', value )
return sendAjax('http://api.apiopen.top/getJoke'{page:1,count:2,type:'video'})
},
reason => { console.log('第1次请求失败了', reason); return new Promise(()=>{})}
)
.then(
value => {
console.log('第2次请求成功了', value )
return sendAjax('http://api.apiopen.top/getJoke'{page:1,count:2,type:'video'})
},
reason => { console.log('第2次请求失败了', reason); return new Promise(()=>{})}
)
4.7 Promise 错误的穿透(传透)?
(1)当使用 promise 的 then 链式调用时,可以在最后指定失败的回调
(2)前面任何操作出了异常,都会传到最后失败的回调中处理
sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'})
.then(
value => {
console.log('第1次请求成功了', value )
return sendAjax('http://api.apiopen.top/getJoke'{page:1,count:2,type:'video'})
},
// reason => { console.log('第1次请求失败了', reason)}
)
.then(
value => {
console.log('第2次请求成功了', value )
return sendAjax('http://api.apiopen.top/getJoke'{page:1,count:2,type:'video'})
},
// reason => { console.log('第2次请求失败了', reason)}
)
.catch(
reason => { console.log('兜底的catch', reason) }
)
# 只要任何一次出错,直接到catch
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('a');
},1000)
})
.then(
value => { console.log('成功了1', value); return 'b';}, //1.
// reason => { console.log('失败了1', reason); return -2} //返回undefined是非promise值
)
.then(
value => { console.log('成功了2', value); return Promise.reject(-108);},
// reason => { console.log('失败了2', reason); return -3;} //2 返回a
)
.catch(
reason => { console.log('兜底的catch', reason) }
)
"成功了1" "a"
"成功了2" "b"
"兜底的catch" -108
相当于这种写法:多写了很多reason => {throw reason}
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('a');
},1000)
})
.then(
value => { console.log('成功了1', value); return 'b';}, //1.
reason => { throw reason } //返回undefined是非promise值
)
.then(
value => { console.log('成功了2', value); return Promise.reject(-108);},
reason => { throw reason} //2 返回a
)
.catch(
reason => { console.log('兜底的catch', reason) }
)
"成功了1" "a"
"成功了2" "b"
"兜底的catch" -108
5. Promise的优势
优势-
- 指定回调函数的方式更加灵活
旧的: 必须在启动异步任务前指定
promise
: 启动异步任务=》返回promise
对象=》给promise
对象绑定回调函数(甚至看在异步任务结束后指定)- 支持链式调用,可以解决回调地狱问题
(1)什么是回调地狱:
回调函数嵌套调用,外部调用函数异步执行的结果是嵌套的回调函数执行的条件
(2)回调地狱的弊端:
代码不利于阅读,不便于异常处理
(3)一个不是很优秀的解决方案:
then
的链式调用
(4)终极解决方案:
async/await
(底层实际上依然使用then的链式调用)
6. async 和 await的使用
async
和await
基本使用
async
修饰的函数
函数返回值为promise
对象
promise
对象的结果由async
函数执行的返回值决定await
表达式
await
右侧的表达式一般为promise
对象,也可以是其他值
(1)如果表达式是promise
对象,await后的返回值是promise成功的值
(2)如果表达式是其他值,直接将其值作为await
的返回值
3.注意:
await
必须写在async
函数中,但是async
函数中可以没有await
(一般不这么用)
如果await
的promise
失败了,就会抛出异常,需要通过try...catch
来捕获处理
# async和 await最基本使用
const p=new Promise((resolve, reject) => {
setTimeout(() => {
resolve('a');
},1000)
})
/*async function demo(){
const result =await p
console.log(result)
}*/
!(async()=>{ //加个感叹号,防止前面没有写分号
const result=await p; //等到p成功的结果
console.log(result)
})
串联多个异步任务
const p1=new Promise((resolve, reject) => {
setTimeout(() => {
resolve('a');
},1000)
})
const p2=new Promise((resolve, reject) => {
setTimeout(() => {
reject('b');
},2000)
})
const p3=new Promise((resolve, reject) => {
setTimeout(() => {
resolve('c');
},4000)
})
!(async()=>{
try{
const result1=await p1;
console.log(result1);
const result2=await p2;
console.log(result2);
const result3=await p3;
console.log(result3);
}
catch(error){
console.log(error);
}
})
6.1 await的应用
!(async()=>{
try{
const result1=await sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'});
console.log('第1次请求成功了',result1);
const result2=await sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'});
console.log('第1次请求成功了',result2);
const result3=await sendAjax('http://api.apiopen.top/getJoke',{page:1,count:2,type:'video'});
console.log('第1次请求成功了',result3);
}
catch(error){
console.log(error);
}
})
6.2 await的原理
若我们使用
async
配合await
这种写法:
- 表面上不出现任何的回调函数
- 但实际上底层把我们写的代码进行了加工,把回调函数“还原”回来了
- 最终运行的代码是依然有回调的,只是程序员没有看见
const p=new Promise((resolve, reject) => {
setTimeout(() => {
resolve('a');
},2000)
})
async function demo(){
const result = await p;
console.log(result)
}
/* #浏览器翻译后的代码(原理)
async function demo(){
p.then(result=>{ console.log(result)},
)
}
*/
demo()
console.log(1)
7. 宏任务和微任务
宏队列:【宏任务1,宏任务2,。。。】
微任务:【微任务1,微任务2,。。。】
规则:每次要执行宏队列里的一个任务之前,先看微队列里是否有待执行的微任务
(1)如果有,先执行微任务
(2)如果没有,按照宏队列里的任务顺序,依次执行
优先级:先主线程=》微队列=》宏队列
# 代码1
setTimeout(() => { #宏任务 进宏队列
console.log('timeout');
},1000)
Promise.resolve(1).then( # 微任务 进微队列
value => { console.log('成功了1', value);},
)
Promise.resolve(2).then( # 微任务 进微队列
value => { console.log('成功了2', value);},
)
console.log('主线程') #主线程
"主线程" "成功了1" 1 "成功了2" 2 "timeout"
# 代码2
setTimeout(() => {
console.log('timeout1');
})
setTimeout(() => {
console.log('timeout2');
})
Promise.resolve(1).then(
value => { console.log('成功了1', value);},
)
Promise.resolve(2).then(
value => { console.log('成功了2', value);},
)
"成功了1" 1 "成功了2" 2 "timeout1" "timeout2"
# 代码3
setTimeout(() => {
console.log('timeout1');
Promise.resolve(5).then(
value => { console.log('成功了5', value);},
)
console.log('timeout3');
})
setTimeout(() => {
console.log('timeout2');
})
Promise.resolve(3).then(
value => { console.log('成功了3', value);},
)
Promise.resolve(4).then(
value => { console.log('成功了4', value);},
)
"成功了3" 3 "成功了4" 4
"timeout1" "timeout3" "成功了5" 5 "timeout2"
# 代码3
setTimeout(() => {
console.log('0');
},0)
new Promise((resolve,reject)=>{ //1
console.log("1")
resolve()
}).then(()=>{ //1.1
console.log("2")
new Promise((resolve,reject)=>{
console.log("3")
resolve()
}).then(()=>{
console.log("4")
}).then(()=>{
console.log("5")
})
}).then(()=>{ //1.2
console.log("6")
})
new Promise((resolve,reject)=>{ //2
console.log("7")
resolve()
}).then(()=>{ //2.1
console.log("8")
})
"1""7""2""3""8""4""6""5""0"