ES6-Promise

基本用法

Promise是一個類,能夠建立實例;【表明承諾,何時會用到承諾,通常是異步任務,就是須要很長時間執行任務(先畫個餅)】json

Promise構造函數接受一個函數做爲參數,該函數的兩個參數分別是resolve和reject。它們是兩個函數,由 JavaScript 引擎提供,不用本身部署promise

new promise = New Promise(function(resolve,reject){
    if(異步操做成功){
      resolve(value)
    }else{
      reject(error)
    }
  })
  1. resolve函數的做用是:將Promise對象的狀態從「未完成」變爲「成功」(既從pending變爲resolved),並將異步操做的結果【成功時2】做爲參數傳遞出去;
  2. reject函數的做用是:將Promise對象的狀態從「未完成」變爲「失敗」(既從pending變爲rejected),異步操做失敗時調用,並將異步操做報出的錯誤,做爲參數傳遞出去。

Promise實例生成之後,能夠用then方法分別指定resolved狀態和rejected狀態的回調函數。app

promise.then(function(value) {
  // success
}, function(error) {
  // failure
});

then方法能夠接受兩個回調函數做爲參數。異步

  • 第一個回調函數是Promise對象的狀態變爲resolved時調用,
  • 第二個回調函數是Promise對象的狀態變爲rejected時調用。
  • 其中,第二個函數是可選的,不必定要提供。這兩個函數都接受Promise對象傳出的值做爲參數。

異步加載圖片

function loadImageAsync(url) {
  return new Promise(function(resolve, reject) {
    const image = new Image();

    image.onload = function() {
      resolve(image);
    };

    image.onerror = function() {
      reject(new Error('Could not load image at ' + url));
    };

    image.src = url;
  });
}

實現的 Ajax 操做

const getJSON = function(url) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    const client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();

  });

  return promise;
};

getJSON("/posts.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('出錯了', error);
});

Promise.prototype.then()

Promise實列具備then方法【獲取Promise成功的值或者失敗的緣由】,能夠說,then方法是定義在Promise對象的原型(prototype)上。函數

then方法返回的是一個新的Promise實例(注意,不是原來那個Promise實例)。所以能夠採用鏈式寫法,即then方法後面再調用另外一個then方法。post

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});
  • promise.then(onfulfilled,onRejected)
  • onfulfilled,onRejected都是函數

上面的代碼使用then方法,依次指定了兩個回調函數。第一個回調函數完成之後,返回一個全新的Promise對象,會將返回結果做爲參數【這個參數就能夠作爲全新的Promise對象的then()中的參數】,傳入第二個回調函數。this

採用鏈式的then,能夠指定一組按照次序調用的回調函數。這時,**前一個回調函數,有可能返回的仍是一個Promise對象(即
有異步操做)**,這時**後一個回調函數,就會等待該Promise對象的狀態發生變化,纔會被調用。**
getJSON("/post/1.json").then(function(post) {
  return getJSON(post.commentURL);
}).then(function (comments) {
  console.log("resolved: ", comments);
}, function (err){
  console.log("rejected: ", err);
});

上面代碼中,第一個then方法指定的回調函數,返回的是另外一個Promise對象。這時,第二個then方法指定的回調函數,就會等待這個新的Promise對象狀態發生變化。若是變爲resolved,就調用第一個回調函數,若是狀態變爲rejected,就調用第二個回調函數。url

Promise.prototype.catch()

getJSON('/posts.json').then(function(posts) {
  // ...
}).catch(function(error) {
  // 處理 getJSON 和 前一個回調函數運行時發生的錯誤
  console.log('發生錯誤!', error);
});

上面代碼中,getJSON方法返回一個 Promise 對象,若是該對象狀態變爲resolved,則會調用then方法指定的回調函數;若是異步操做拋出錯誤,狀態就會變爲rejected,就會調用catch方法指定的回調函數,處理這個錯誤。另外,then方法指定的回調函數,若是運行中拋出錯誤,也會被catch方法捕獲prototype

相關文章
相關標籤/搜索