promise async await 结合 demo1

// 模拟 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 方式 begain
const getByApi1 = async ()=> {
    try {
        const data = await post1()
        console.log('getP1 try 2s')
        return data
    }catch(e){
        console.log('getP1 catch 2s')
        return e
    }
}
const getByApi2 = async ()=> {
    try {
        const data = await post2()
        console.log('getP2 try 1s')
        return data
    }catch(e){
        console.log('getP2 catch 1s')
        return e
    }
}
const getByApi3 = async ()=> {
    try {
        const data = await post3()
        console.log('getP3 try 3s')
        return data
    }catch(e){
        console.log('getP3 catch 3s')
        return e
    }
}
const getByApi4 = async ()=> {
    try {
        const data = await post4()
        console.log('getP4 try 4s')
        return data
    }catch(e){
        console.log('getP4 catch 4s')
        return e
    }
}
// 模拟 post 异步接口   try catch 方式 end

  3、

Promise.all([getByApi1(), getByApi2(), getByApi3(), getByApi4()]).then((result) => {
    console.log('result')
    console.log(result)
}).catch((error) => {
    console.log('error')
    console.log(error)
})

  4、看结果

1s后,console.log 'getP2 try 1s'  ;

2s后,console.log 'getP1 try 2s' ; 

 3s后,console.log 'getP3 try 3s';

4s后,console.log 'getP3 try 3s';

然后 

result
["reject 2000", "success 1000", "success 3000", "reject 4000"]
getP2 try 1s
getP1 catch 2s
getP3 try 3s
getP4 catch 4s
result
["reject 2000", "success 1000", "success 3000", "reject 4000"]

  

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