Promise

Promise是一种用于处理异步操作的对象(解决了回调地狱的问题)

它有三种状态: pedding (进行中)      resolve(已成功)     rejected(已失败) 

pedding  => resolve  或  pedding => rejected(状态一旦变更,就无法再次变更了,是什么就是什么了,板上钉钉 )

了解Promise前可以在控制台打印看一下它自身都有哪些方法 ,使用console.dir(Promise)

Promise常用方法有.then()  .catch()   .reject()   .resolve() ,Promise是构造函数,使用new创造实例

let promise = new Promise((resolve,reject)=>{

           setTimeout(()=>{

                      resolve('成功信息‘)

                      console.log(yes)

           },1000)

}).then(    //then如果只有一个参数,那么就是可以接收到promise对象的成功返回值,两个参数的话:第一个参数代表成功返回的值,第二个参数是失败返回的值

res=>{console.log(res)},     // 这里打印的是成功信息,也就是上面resolve的内容   (then的第一个参数)

reason=>{console.log(reason)}                          //这里可以捕获到失败信息,也就是reject的内容   (then的第二个参数)

).catch(reasson=>{

console.log(reason)                //这里捕获到失败信息,也就是reject的内容 

})

 

Promise.all([arr1,arr2,arr3]).then(res=>{console.log(res)})     // 等待所有promise都成功返回,才会进入then,否则就会进入到catch

Promise需要注意一个面试题:如果其中promise一个抛出异常了,还想让其他的promise继续执行怎么办?

                                                 : 在catch里面resolve就行了  .catch(err => { return Promise.resolve("xxxxxx") })

Promise.race([arr1,arr2,arr3]).then(res=>{console.log(res)}).catch(reason=>{console.log(reason))   //  哪一个Promise最先返回,无论是resolve还是reject (要最先返回的那个)    

 

posted @   爱吃蔬菜的小红帽  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示