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

  二、javascript

// 模擬 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

  三、java

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

  四、看結果異步

1s後,console.log 'getP2 try 1s'  ;async

2s後,console.log 'getP1 try 2s' ; post

 3s後,console.log 'getP3 try 3s';blog

4s後,console.log 'getP3 try 3s';接口

而後 ip

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"]
相關文章
相關標籤/搜索