async/awiat 实例详解
2020-07-06 本文已影响0人
loushumei
背景:
异步回调:callback hell
Promise than catch 链式调用,也是基于回调函数.
async/await是用同步语法写异步
function loadImg(src) {
return new Promise(
//参数 resolve reject 均是函数
(resolve, reject) => {
const img = document.createElement('img')
img.onload = () => {
resolve(img)
}
img.onerror = () => {
const err = new Error(`图片加载失败!${src}`)
reject(err)
}
img.src = src
}
)
}
const url1 = 'https://img3.mukewang.com/5686a790000124f701000100-100-100.jpg'
const url2 = 'https://img3.mukewang.com/5686a790000124f701000100-100-100.jpg'
!(async function(){
console.log('start')
const img1 = await loadImg(url1)
console.log(img1.width)
const img2 = await loadImg(url2)
console.log(img2.height)
})()//立即执行函数
async/await与Promise的关系 *****
- 执行async函数,返回的是Promise对象
await相当于Promise的then
async function fn1() {
return 100
}
console.log(fn1()) //Promise {<resolved>: 100}
fn1().then(data => {
console.log(data) //100
})
// 执行async函数,返回的是Promise对象
!(async function(){
const data = await Promise.resolve(300) // await相当于Promise的then
console.log(data)//300
const data2 = await 400
console.log(data2) //400
const data3 = await fn1() //执行async函数 返回的promise对象
console.log(data3) //100
})()
- try..catch可捕获异常,代替了Promise的catch
!(async function(){
const p=Promise.reject('err')
try{
const res =await p
console.log(res)
}catch(ex){
console.error(ex) //err : try..catch可捕获异常,代替了Promise的catch
}
})()
async/await是语法糖,异步的本质
async/await是语法层面解决异步的回调
JS还是单线程,还是得有异步,还得是基于event loop
async/await只是一个语法糖
async function async1() {
console.log('async1 start') //2
await async2() //立马执行async2 返回undefined
//await后面,都可以看作是calback里的内容,即异步
console.log('async1 end')//5 异步代码
}
async function async2() {
console.log('async2')//3
}
console.log('script start')//1
async1() //立马执行
console.log('script end')//4
// script start
// async1 start
// async2
// script end
// async1 end
// ----------------------------------------------
async function async1() {
console.log('async1 start')//2
await async2()
// 以下三行都是 async2 的异步回调callback的内容
console.log('async1 end')
await async3()
//以下一行是async3 的异步回调callback的内容
console.log('async1 end 2')
}
async function async2() {
console.log('async2')
}
async function async3() {
console.log('async3')
}
console.log('script start') //1
async1()
console.log('script end')
// script start
// async1 start
// async2
// script end
// async1 end
// async3
// async1 end 2
异步的本质是什么?
JS是单线程的,异步需要回调
for of的使用
function muti(num) {
return new Promise(resolve => {
setTimeout(() => {
resolve(num * num)
}, 1000);
})
}
const nums = [1, 2, 3]
!(async function () {
for (const i of nums) {
const res = await muti(i)
console.log(res)
}
})()