promise async await 结合 demo2

// 模拟 post 异步接口 begain
let post1 = ()=> {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            reject('reject 2000')
        } , 2000)
    })
}
let post2 = ()=> {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve('success 1000')
        } , 1000)
    })
}
let post3 =  ()=> {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve('success 3000')
        } , 3000)
    })
}
let post4 =  ()=> {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            reject('reject 4000')
        } , 4000)
    })
}
// 模拟 post 异步接口 end

  2、


// 模拟 post 异步接口 try catch 方式 end
const getByApi5 = ()=> {
return new Promise(async (resolve, reject)=>{
try {
const data = await post1()
console.log('getP5 try 2s')
resolve(data)
}catch(e){
console.log('getP5 catch 2s')
reject(e)
}
})
}
const getByApi6 = ()=> {
return new Promise(async (resolve, reject)=>{
try {
const data = await post2()
console.log('getP6 try 1s')
resolve(data)
}catch(e){
console.log('getP6 catch 1s')
reject(e)
}
})
}
const getByApi7 = ()=> {
return new Promise(async (resolve, reject)=>{
try {
const data = await post3()
console.log('getP7 try 3s')
resolve(data)
}catch(e){
console.log('getP7 catch 3s')
reject(e)
}
})
}
const getByApi8 = ()=> {
return new Promise(async (resolve, reject)=>{
try {
const data = await post4()
console.log('getP8 try 4s')
resolve(data)
}catch(e){
console.log('getP8 catch 4s')
reject(e)
}
})
}

  3、

Promise.all([getByApi5(), getByApi6(), getByApi7(), getByApi8()]).then((result) => {
    console.log('result')
    console.log(result)
}).catch((error) => {
    console.log('error')
    console.log(error)
})

  4、区别在于, 2s 后, 走catch( error, 返回 reject 2000),  不会走 then

getP6 try 1s
getP5 catch 2s
error
reject 2000
getP7 try 3s
getP8 catch 4s

  

posted on 2018-11-23 17:13  至尊宝第一代  阅读(195)  评论(0编辑  收藏  举报