国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

ES6 Promise對象的應(yīng)用實例分析

2024-05-06 15:37:25
字體:
供稿:網(wǎng)友

本文實例講述了ES6 Promise對象的應(yīng)用。分享給大家供大家參考,具體如下:

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Promise 對象用于一個異步操作的最終完成(或失敗)及其結(jié)果值的表示。簡單點說,它就是用于處理異步操作的,異步處理成功了就執(zhí)行成功的操作,異步處理失敗了就捕獲錯誤或者停止后續(xù)操作。

在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);});            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 敖汉旗| 宣汉县| 临武县| 尚志市| 和林格尔县| 全南县| 兴城市| 甘孜| 临湘市| 安西县| 台南县| 庐江县| 黔江区| 忻城县| 胶州市| 娄烦县| 漾濞| 小金县| 洮南市| 茶陵县| 阜新| 新余市| 屯昌县| 环江| 隆化县| 新安县| 云梦县| 溆浦县| 五河县| 石阡县| 昌宁县| 黄石市| 南安市| 南城县| 城步| 正定县| 汕尾市| 临湘市| 阳西县| 泸州市| 兴业县|