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

首頁 > 開發 > JS > 正文

Promise掃盲貼

2024-05-06 16:52:42
字體:
來源:轉載
供稿:網友

then

then函數可以return另一個promise:

const p1 = new Promise((resolve, reject) =>{  resolve('p1')})const p2 = new Promise((resolve, reject) =>{ setTimeout(() =>{  resolve('p2') },3000)})p1.then(res => { console.log(res)  return p2}).then(res =>{   // p2 resolve后才執行  console.log(res)})//p1// 3s后輸出...// p2

那么這個p2就會代替當前p1的狀態,等到新的p2的狀態修改時,下一個then才會執行

catch

1. 作用

可以捕獲到promise程序執行中的error,等同于  .then(null, rejection)  或  .then(undefined, rejection)

2. 可以獲取到的錯誤

promise函數體中拋出的error。在promise resolve后,再拋出錯誤,不會被捕獲

const p1 = new Promise((resolve,reject) => {throw new Error('error')})p1.catch(error => console.log(error))  // Error: error

promise的reject操作

const p2 = new Promise((resolve,reject) => reject('rejected'))p2.catch(error => console.log(error)) // rejected

then 函數體中拋出的error

const p3 = new Promise((resolve,reject) => resolve('resolved'))p3.then(res =>{  throw new Error('error')}).catch(error => console.log(error)) // Error: error

then函數可以返回一個promise(如果沒有定義catch方法),如果這個promise函數體中有reject或者error,也可以捕獲到

3. 推薦使用catch方式捕獲錯誤,而不是then的第二個參數:

因為catch可以捕獲到它前面所有then方法中的錯誤

finally

  • 不管promise最后狀態如何,都會執行的操作
  • 沒有參數,獲取不到當前promise最后的狀態

Promise.all

1. 參數

參數不僅僅可以是數組,具有Iterator接口的對象都可以。
數組參數的每一個元素為promise實例,如果不是,就會調用Promise.resolve轉換為Promise實例

const obj = {  [Symbol.iterator]() {    let index = 0    return {      next() {        return {          // promise對象 和 其他類型都可以          value: new Promise(resolve => resolve(index++)), done: index > 2          // value: index++, done: index > 2        }      }    }  }}const p = Promise.all(obj)p.then(res => {  console.log(res) // [0, 1]}) 

2. 狀態

const p = Promise.all([p1, p2, p3]);

p的狀態由p1、p2、p3決定,分成兩種情況:

  • 只有p1、p2、p3的狀態都變成fulfilled,p的狀態才會變成fulfilled,此時p1、p2、p3的返回值組成一個數組,傳遞給p的回調函數。
  • 只要p1、p2、p3之中有一個被rejected,p的狀態就變成rejected,此時第一個被reject的實例的返回值,會傳遞給p的回調函數。

3. catch

如果參數中的promise定義了catch方法,那么Promise.all()的catch就不會捕獲到錯誤

Promise.race

  • 只要p1、p2、p3之中有一個實例率先改變狀態,p的狀態就跟著改變。那個率先改變的 Promise 實例的返回值,就傳遞給p的回調函數。
  • 參數、catch規則同Promise.all

Promise.resolve

將現有對象轉為Promise對象。

1. 參數

  • 參數為promise實例:原封不動的返回這個實例。
  • 參數為thenable對象:將它轉為promise對象,然后立即執行它的then方法
  • 參數不是thenable對象,或者是一個原始值:返回一個新的promise對象,狀態為resolved
  • 沒有參數:直接返回衣蛾resolved狀態的promise對象

Promise.reject

返回一個狀態為rejected的promise實例

Promise.reject()方法的參數,會原封不動地作為reject的理由,變成后續方法的參數

const thenable = { then(resolve, reject) {  reject('error'); }};Promise.reject(thenable).catch(e => { console.log(e === thenable)})// true e并不是'error'

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 英吉沙县| 彭水| 蓝田县| 扶沟县| 荆州市| 西乡县| 岱山县| 荥阳市| 彭泽县| 台江县| 威远县| 社旗县| 岳阳市| 会昌县| 思茅市| 嘉鱼县| 孟连| 盱眙县| 泽库县| 克东县| 辰溪县| 平舆县| 三亚市| 揭西县| 旌德县| 岳池县| 禹城市| 三门县| 千阳县| 池州市| 桐梓县| 勃利县| 滦平县| 兴业县| 岢岚县| 徐州市| 西林县| 绩溪县| 涟水县| 靖州| 楚雄市|