前言
promise使用.then解决回调地狱,基于回调函数
async/await是更加优雅的解决异步编程的写法:
- 消灭异步回调的最优方法
它是同步语法,也就是说用同步的写法写异步的代
//里面函数为AJAX,因此是异步任务
let loadImg = (url)=>{
const p = new Promise((resolve,reject)=>{
let newImg = document.createElement("img")
newImg.src = url
newImg.onload = function(){
resolve(newImg)
}
newImg.error = function(){
reject(new Error('Could not load Image at url'))
}
})
return p
}
//通过 .then 来获取结果
loadImg(url1)
.then((img)=>{
console.log(img.width,img.height)
document.body.appendChild(img)
return loadImg(url2)
})
.then((img)=>{
console.log(img.width,img.height)
document.body.appendChild(img)
})
.catch((err)=>{
console.log(err)
})
//使用 async 和 await 的方法来写,立即执行函数
(async function(){
// loadImg(url1) 返回 promise 对象
// await 可以拿到从 resolve 传递过来的 dom 对象
const img1 = await loadImg(url1)
document.body.appendChild(img1)
const img2 = await loadImg(url2)
document.body.appendChild(img2)
})()
//await 接 async 函数
async function loadImg1(){
const img1 = await loadImg(url1)
return img1
}
(async function(){
//img1可以拿到 resolve 里面的值
const img1 = await img1
document.body.appendChild(img1)
})()
async/await和promise的关系
- async/await 是消灭异步回调的终极武器
- 但和Promise并不排斥,两者相辅相成
- 执行 async 函数,返回的是 Promsie 对象
- await 相当于 Promise 的 then ,then指的是成功,不指失败
- try…catch 可捕获异常,代替了 Promise的 catch
await
- await后面接Promise
- await和then的区别:then还需要传回调回去,但await可以直接得到值
- await后面跟的不是promise对象而是数值,会自动包装成成功状态的promise对象
- await接promise为空:
- 什么都打印不出,因为new Promise里面没有任何状态改变,而await一直再等状态改变
- 因为只有状态改变了,await才允许执行后面的代码
- await接promise为error:
- 会报错
- await相当于成功状态的.then,然而都没有成功,因此不会执行后面的代码
- 因为JS是单线程
- 使用try...catch捕获error——捕获到错误就不会影响后面的输出
async和await实质
- Promise一般用来解决层层嵌套的回调函数
- async/await 是消灭异步回调的终极武器
- JS还是单线程,还是得有异步,还是得基于 event loop(轮询机制)
- async/await 只是一个语法糖