Promise的用途

  • 规范回调的名字和顺序
  • 拒绝回调地狱,让代码可读性更强
  • 很方便的捕获错误

    创建Promise

    1. //用定时器模拟异步请求
    2. function getData(x){
    3. return new Promise((resolve, reject)=>{
    4. setTimeout(function(){
    5. if(x){
    6. resolve(x)
    7. }else{
    8. reject('404')
    9. }
    10. },Math.random()*1000+1)
    11. })
    12. }

    Promise.prototype.then

    1. getData(1)
    2. .then(function(x){
    3. console.log(x)
    4. return getData(2)
    5. }, e=>{console.log(e)})
    6. .then(function(x){
    7. console.log(x)
    8. return getData(3)
    9. }, e=>{console.log(e)})
    10. .then(function(x){
    11. console.log(x)
    12. }, e=>{console.log(e)})
    then方法接受两个函数(注意是函数,不要直接调用函数,调用的函数会立即执行
    成功的时候执行第一个函数,失败的时候执行第二个函数

    Promise.all

    当我们需要获得多个数据才进行下一步时使用Promise.all
    1. let group = Promise.all([getData(22),getData(66),getData(1024),getData(-33)])
    2. group.then(
    3. function(arr){
    4. let sum = 0
    5. arr.forEach(item => sum+=item)
    6. console.log(sum)
    7. },e => {console.log(e)}).catch(e=>{console.log(e)})
    Promise.all需要传入一个数组,数组中的元素都是Promise对象,当这些对象都执行成功,执行then中的第一个函数(成功函数),失败时只能获得第一个失败Promise的错误数据
    Promise.all是大家一起到终点,一个失败全都失败

    Promise.race

    1. let group2 = Promise. race([getData(22),getData(),getData(1024),getData(-33)])
    2. group2.then(
    3. function(arr){
    4. console.log(`我拿到数据了!${arr}`)
    5. },e => {console.log(e)})
    Promise.race和Promise.all相对应,哪个Promise对象最快得到结果,就最先用谁的结果(只要快就行,不管失败还是成功)