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

首頁 > 網站 > 幫助中心 > 正文

node.js Promise對象的使用方法實例分析

2024-07-09 22:42:59
字體:
來源:轉載
供稿:網友

本文實例講述了node.js Promise對象的使用方法。分享給大家供大家參考,具體如下:

Promise對象是干嘛用的?

將異步操作以同步操作的流程表達出來

一、Promise對象的定義

let flag = true;const hello = new Promise(function (resolve, reject) {  if (false) {//異步操作成功    resolve("success");  } else {    reject("error");  }});

二、鏈式調用-then方法

使用then方法調用,第一個參數是成功回調,第二個參數是失敗回調,如下

hello.then(  function (value) {    console.log(value)  },  function (err) {    console.log(err)  });

下面我們分別定義三個方法,參數為延時執行的秒數

chenqionghe get muslce
function chenqionghe(second) {  return new Promise((resolve, reject) => {    setTimeout(function () {      console.log("chenqionghe");      resolve();    }, second * 1000);  })}function get(second) {  return new Promise((resolve, reject) => {    setTimeout(function () {      console.log("get");      resolve()    }, second * 1000);  })}function muscle(second) {  return new Promise((resolve, reject) => {    setTimeout(function () {      console.log("muscle");      resolve();    }, second * 1000);  })}

調用如下

chenqionghe(3)  .then(function () {    return get(2)  })  .then(function () {    return muscle(1)  });

運行輸出

chenqionghe
get
muscle

這樣就實現了鏈式的調用,相當于同步的方式執行了

如果不使用then調用,會發生什么情況?如下

chenqionghe(3);get(2);muscle(1);

結果如下

muscle
get
chenqionghe

我們看到chenqionghe雖然是第一個執行,卻是最后輸出內容,因為設置了3秒后執行

重點:

Promise 對象的錯誤具有“冒泡”性質,會一直向后傳遞,直到被捕獲為止。也就是說,錯誤總是會被下一個catch語句捕獲。 一般來說,不要在then方法里面定義 Reject 狀態的回調函數(即then的第二個參數),總是使用catch方法。

三、捕獲異常-catch

chenqionghe(3)  .then(function () {    return get(2)  })  .then(function () {    throw new Error("abc");    return muscle(1)  })  .catch(function (e) {    console.log("異常:" + e.message)  });

輸出

chenqionghe
get
異常:abc

異常本質也是一個Promise,所以后面還可以執行then

chenqionghe(3)  .then(function () {    return get(2)  })  .then(function () {    throw new Error("abc");    return muscle(1)  })  .catch(function (e) {    console.log("異常:" + e.message)  })  .then(function () {    console.log("異常后執行")  });

運行輸出

chenqionghe
get
異常:abc
異常后執行

四、收尾執行-finally

就是不管怎么樣,都會執行的方法,即使是拋異常了

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 海城市| 龙海市| 遂平县| 嘉黎县| 林甸县| 滦南县| 浑源县| 利辛县| 靖西县| 墨玉县| 巴彦淖尔市| 依兰县| 宁南县| 贵定县| 酒泉市| 牙克石市| 太白县| 乐东| 左贡县| 阿瓦提县| 枣阳市| 许昌县| 赤城县| 观塘区| 长乐市| 什邡市| 锡林郭勒盟| 台北县| 太仆寺旗| 东安县| 景谷| 阿合奇县| 莱西市| 河东区| 根河市| 贡山| 石泉县| 蚌埠市| 高平市| 崇州市| 芜湖县|