溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ES6中怎么使用Promise對象

發(fā)布時間:2021-06-17 16:32:10 來源:億速云 閱讀:120 作者:Leah 欄目:web開發(fā)

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)ES6中怎么使用Promise對象,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

在promise之前處理異步回調(diào)的方式

function asyncFun(a,b,callback) {
   setTimeout(function () {
    callback(a+b);
   },200);
  }
  asyncFun(1,2, function (res) {
   if(res > 2) {
    asyncFun(res, 2, function (res) {
     if(res > 4) {
      asyncFun(res, 2, function (res) {
       console.log('ok');
       console.log(res);
      })
     }
    })
   }
  });

從上面可以看出所謂的”回調(diào)地獄”的可怕

使用promise來優(yōu)雅的處理異步

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
asyncFun(1,2)
.then(function (res) {
 if(res > 2) {
  return asyncFun(res, 2);
 }
})
.then(function (res) {
 if(res > 4) {
  return asyncFun(res, 2);
 }
})
.then(function (res) {
 console.log('ok');
 console.log(res);
})
.catch(function (error) {
 console.log(error);
});

使用promise處理內(nèi)部異常的舉例

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  // 模擬異常判斷
  if(typeof a !== 'number' || typeof b !== 'number') {
   reject(new Error('no number'));
  }
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
asyncFun(1,2)
.then(function (res) {
 if(res > 2) {
  return asyncFun(res, 2);
 }
},function (err) {
 console.log('first err: ', err);
})
.then(function (res) {
 if(res > 4) {
  return asyncFun(res, 'a');
 }
},function (err) {
 console.log('second err: ', err);
})
.then(function (res) {
 console.log('ok');
 console.log(res);
},function (err) {
 console.log('third err: ', err);
});

從上面可以看出通過then的第二個回調(diào)函數(shù)處理promise對象中的異常,通過reject返回異常的promise對象

通過catch統(tǒng)一處理錯誤,通過finally執(zhí)行最終必須執(zhí)行的邏輯

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  // 模擬異常判斷
  if(typeof a !== 'number' || typeof b !== 'number') {
   reject(new Error('no number'));
  }
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
asyncFun(1,2)
.then(function (res) {
 if(res > 2) {
  return asyncFun(res, 2);
 }
})
.then(function (res) {
 if(res > 4) {
  return asyncFun(res, 'a');
 }
})
.then(function (res) {
 console.log('ok');
 console.log(res);
})
.catch(function (error) {
 console.log('catch: ', error);
})
.finally(function () {
 console.log('finally: ', 1+2);
});

通過Promise.all()靜態(tài)方法來處理多個異步

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
var promise = Promise.all([asyncFun(1,2), asyncFun(2,3), asyncFun(3,4)])
promise.then(function (res) {
 console.log(res); // [3, 5, 7]
});

通過Promise.race()靜態(tài)方法來獲取多個異步中最快的一個

function asyncFun(a,b,time) {
 return new Promise(function (resolve, reject) {
  setTimeout(function() {
   resolve(a + b);
  },time);
 })
}
var promise = Promise.race([asyncFun(1,2,10), asyncFun(2,3,6), asyncFun(3,4,200)])
promise.then(function (res) {
 console.log(res); // 5
});

通過Promise.resolve() 靜態(tài)方法來直接返回成功的異步對象

var p = Promise.resolve('hello');
p.then(function (res) {
 console.log(res); // hello
});

等同于,如下:

var p = new Promise(function (resolve, reject) {
 resolve('hello2');
})
p.then(function (res) {
 console.log(res); // hello2
});

通過Promise.reject() 靜態(tài)方法來直接返回失敗的異步對象

var p = Promise.reject('err')
p.then(null, function (res) {
 console.log(res); // err
});

等同于,如下:

var p = new Promise(function (resolve, reject) {
 reject('err2');
})
p.then(null, function (res) {
 console.log(res); // err
});

通過一個小例子來測試Promise在面向?qū)ο笾袘?yīng)用

'use strict';
class User{
 constructor(name, password) {
  this.name = name;
  this.password = password;
 }
 send() {
  let name = this.name;
  return new Promise(function (resolve, reject) {
   setTimeout(function () {
    if(name === 'leo') {
     resolve('send success');
    }else{
     reject('send error');
    }
   });
  });
 }
 validatePwd() {
  let pwd = this.password;
  return new Promise(function (resolve, reject) {
   setTimeout(function () {
    if(pwd === '123') {
     resolve('validatePwd success');
    }else{
     reject('validatePwd error');
    }
   });
  })
 }
}
let user1 = new User('Joh');
user1.send()
 .then(function (res) {
  console.log(res);
 })
 .catch(function (err) {
  console.log(err);
 });
let user2 = new User('leo');
user2.send()
 .then(function (res) {
  console.log(res);
 })
 .catch(function (err) {
  console.log(err);
 });
let user3 = new User('leo', '123');
user3.validatePwd()
 .then(function (res) {
  return user3.validatePwd();
 })
 .then(function (res) {
  console.log(res);
 })
 .catch(function(error) {
  console.log(error);
 });
let user4 = new User('leo', '1234');
user4.validatePwd()
 .then(function (res) {
  return user4.validatePwd();
 })
 .then(function (res) {
  console.log(res);
 })
 .catch(function(error) {
  console.log(error);
 });

上述就是小編為大家分享的ES6中怎么使用Promise對象了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI