promise
使用 .then
链式调用,但也是基于回调函数async/await
更加优雅的异步编程的写法案例1:promise异步加载图片
//里面函数为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)
})()
1.async
async function fn(){
return 100
}
console.log(fn()) //返回一个成功态的promise对象,result 是 100
fn().then(
data=>{
console.log(data)
}
) // 100
2.await
p1.then
,并且只是成功态的then
(async function(){
const p1 = Promise.resolve(300) //一个成功态的promise对象,且传了result为300
const res = await p1 // return 值
console.log(res) // 300
})
fn().then(
data=>{
console.log(data)
}
)
//await直接通过返回值来接收daita, return data
const res = await fn()
(async function(){
const res = await 400 //Promise.resolve(400)
console.log(res) //400
})()
(async function(){
const res = await fn() //fn()会返回promise对象,原理一样
console.log(res) //400
})()
(async function(){
const p = new Promise(()=>{})
const res = await p
console.log(res)
console.log("success")
})()
(async function(){
const p = Promise.reject("error")
const res = await p
console.log(res)
console.log("success")
})() //什么都打印不出来
(async function(){
const p = Promise.reject("error")
try{
const res = await p
console.log(res)
}catch(error){
console.log(error)
}
console.log("success")
})() //打印出 error 和 success
function timeout(){
return new Promise(resolve=>{
setTimeout(()=>{
console.log(1)
resolve()//成功态
})
})
}
//情况一
async function fn(){
timeout()
console.log(2)
}
fn() //打印出 2 一秒后 1
//情况2
async function fn(){
await timeout()
console.log(2)
}
fn() //1秒后打印出 1 2
//写法二
function timeout(){
return new Promise(resolve=>{
setTimeout(()=>{
resolve(1)//成功态,传递参数1
})
})
}
async function fn(){
const res = await timeout() //需要一个变量来接收await return的参数
console.log(res)
console.log(2)
}
fn() //1秒后打印出 1 2
案例2 :请求多份数据,但后一份数据的请求必须依赖上一份数据的请求结果
async function getDate(){
const res1 = await request("./a.json")
console.log(res1)
const res1 = await request("./b.json")
console.log(res2)
const res1 = await request("./c.json")
console.log(res3)
}