首頁  >  文章  >  web前端  >  介紹ES6之Promise對象

介紹ES6之Promise對象

坏嘻嘻
坏嘻嘻原創
2018-09-14 14:11:181382瀏覽

今天討論的新功能讓我非常興奮,因為這個特性是 ES6 中最神奇的特性。         

簡介

Promise物件是非同步程式設計的解決方案。所謂Promise,簡單來說就是一種容器,裡麵包含未來可能結束的一個事件的結果。 

Promise包含三種狀態,pending,fulfilled,rejected。
表現為從pending到fulfilled,或是從pending到rejected。

下面是一個Promise實例的生成

// es5 写法
 const promise = new Promise(function(resolve, reject) {
        if (/*这里填写操作(一般是异步操作)*/) {
            resolve(value);
        } else {
            reject(error)
        }
    })
   // es6 写法,以后默认使用es6语法   const promiseEs = new Promise((resolve, reject) => {        if (/*操作*/) {
            resolve(value);
        } else {
            reject(error);
        }
    })

操作部位一般是一個非同步方法,resolve和reject是es6官方給的方法可以取得到操作部位的返回結果

promise的使用

    promise.then((value) => {        console.log("success" + value);
    }, (error) => {        console.log("error" +error);
    })

then方法接受兩個回呼函數作為參數,第一個方法在Promise物件狀態從pending變成fulfilled時調用,第二個方法在狀態從pending變成rejected時候呼叫。
另外 上面的使用方法可以寫成類似try/catch的形式,將rejected時的處理剝離出來放到catch裡面處理。
promise的使用2

    promise.then((value) => {        console.log("success" + value);
    }).catch((error) => {        console.log("error" +error);
    })

 相關推薦:

ES6的新功能概覽_javascript技巧

#詳解JavaScript ES6中的Generator_基礎學

#

以上是介紹ES6之Promise對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn