ES6學習筆記(四):異步操作


Promise

Promise三種狀態

pending、resolved、rejected

使用語法

var promis = new Promise(function(resolve,reject){
  $.ajax({
    url:'/api/something.json',
    method:'get',
    datatype:'json',
    success:(res) =>{
      resolve(res)
    },
    error:(err)=>{
      reject(err)
    }
  })
})

promis.then(function(res){
  console.log(res)
}).catch(function(err){
  console.log(err)
});

Promise.prototype.then()

鏈式調用,狀態變為resolve
如果把下一步想要的東西return出去,即可讓下一個then使用

var promise = new Promise(function(resolve,reject){
  $.ajax({
    url:'/api/poisearch.json',
    method:'get',
    datatype:'json',
    success:(res) =>{
      resolve(res)
    },
    error:(err)=>{
      reject(err)
    }
  })
})

promise.then(function(res){
  return res.data
}).then(function(data){
  return data.result;
}).then(function(result){
  console.log(result)
});

上面的代碼還可以借用箭頭函數簡寫成,極大提升了代碼的簡潔性和可讀性

promise.then(res => res.data)
  .then(data => data.result)
  .then(result => console.log(result));

Promise.prototype.catch()

如果異步操作拋出錯誤,狀態就會變為Rejected,就會調用catch方法指定的回調函數,處理這個錯誤。

  1. 另外,then方法指定的回調函數,如果運行中拋出錯誤,也會被catch方法捕獲。
  2. 如果Promise狀態已經變成Resolved,再拋出錯誤是無效的。
  3. catch方法返回的還是一個Promise對象,因此后面還可以接着調用then方法。

Promise.all()

多個Promise實例,包裝成1個,有點類似Array.prototype.every()
用法:

var p = Promise.all([p1, p2, p3]);
  1. 只有p1、p2、p3的狀態都變成fulfilled,p的狀態才會變成fulfilled,此時p1、p2、p3的返回值組成一個數組,傳遞給p的回調函數。
  2. 只要p1、p2、p3之中有一個被rejected,p的狀態就變成rejected,此時第一個被reject的實例的返回值,會傳遞給p的回調函數。

Promise.race()

多個Promise實例,包裝成1個,有點類似Array.prototype.some()

  1. p1、p2、p3其中一個狀態變成fulfilled,p的狀態就會變成fulfilled
  2. 那個率先改變的Promise實例的返回值,就傳遞給p的回調函數。

done()、finally()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM