promise和async/await

Posted on 2020-09-22 21:47  猫头唔食鱼  阅读(157)  评论(0编辑  收藏  举报
1.promise resolve之后还会继续执行,如果不想resolve之后继续执行,可以加上return
 let p =  ()=>{
            return new Promise(resolve=>{
                setTimeout(()=>{
                    resolve('data')
                    console.log('会继续执行');
                },500)
            })
        }
let p2 = ()=>{
            return new Promise(resolve=>{
                setTimeout(()=>{
                  return   resolve('data2')
                  console.log('不会继续执行');
                },290)
            })
        }
2.async的使用
async表明该方法是异步的,async方法返回的是promise对象,用then获取结果
 let a = async ()=>{
           return  'data3'
        }
        a().then(res=>{
            console.log(res);
        })
3.async/await 和 Promise一起使用
let p3 = ()=>{
            return new Promise(resovle=>{
                setTimeout(() => {
                    let p3Data = 'p3Data'
                    resovle(p3Data)
                }, 2000);
            })
        }

        let p4 = ()=>{
            return new Promise(resovle=>{
                setTimeout(() => {
                    let p4Data = 'p4Data'
                    resovle(p4Data)
                }, 3000);
            })
        }

        let a3 = async ()=>{
            let data3 = await p3()
            let data4 = await p4()
              // 操作数据
             return data3 + data4
        }

       a3()