Promise對象---淺析

ES 6 中Promise對象的出現爲了解決JS異步編程的問題。
javascript

一個 Promise 對象能夠理解爲一次將要執行的操做(經常被用於異步操做),使用了 Promise 對象以後能夠用一種鏈式調用的方式來組織代碼,讓代碼更加直觀。並且因爲 Promise.all 這樣的方法存在,能夠讓同時執行多個操做變得簡單。java

Promise對象的三種狀態:編程

    1.Fulfilled -----成功
promise

    2.Rejected------失敗異步

    3.pending -----promise對象實例建立的初始狀態
ide


Promise對象的兩個重要方法:----resolve(成功) && reject(失敗)
異步編程

resolve 方法能夠使 Promise 對象的狀態改變成成功,同時傳遞一個參數用於後續成功後的操做。函數

reject 方法則是將 Promise 對象的狀態改變爲失敗,同時將錯誤的信息傳遞到後續錯誤處理的操做。url

function helloWorld (ready) {    

        return new Promise(function (resolve, reject) {        
        if (ready) {
            resolve("Hello World!");  //成功時調用的參數
        } else {
            reject("Good bye!");    //失敗時調用的參數
        }
    });
}

helloWorld(true).then(function (message) {
    alert(message);
}, function (error) {
    alert(error);
});


then方法: then(onFulfilld, onRejected) spa

根據 Promise 對象的狀態來肯定執行的操做,resolve 時執行第一個函數(onFulfilled),reject 時執行第二個函數(onRejected)。


function printHello (ready) {    

     return new Promise(function (resolve, reject) {        
         if (ready) {
            resolve("Hello");
        } else {
            reject("Good bye!");
        }
    });
}function printWorld () {
    alert("World");
}function printExclamation () {
    alert("!");
}

printHello(true)
    .then(function(message){
        alert(message);
    })
    .then(printWorld)
    .then(printExclamation);
相關文章
相關標籤/搜索