利用Promise是解決JS異步執行時候回調函數嵌套回調函數的問題, 更簡潔地控制函數執行流程;
通過new實例化Promise, ?構造函數需要兩個參數, 第一個參數為函數執行成功以后執行的函數resolve, 第二個函數為函數執行失敗以后執行的函數reject:
new Promise(function(resolve , reject) { });
通過Promise,我們把回調函數用線性的方式寫出來,而不是一層套一層, 這個函數有四層回調;
fn("args", function(a) {fn1("foo", function(b) {fn2("bar", function(c) {fn3("baz", function(d) {alert("回調成功,獲知的內容為:"+a+b+c+d)})})}) })
以上的Demo只有包含成功的回調, 如果失敗的回調也算的話, 也就更麻煩了;
如果使用Promise的方式,我們可以改裝成線性的代碼, 更加符合閱讀習慣,只要在then函數下寫邏輯即可;
new Promise(function(resolve , reject) {resolve(1); }).then(function(val) {console.log(val);return new Promise(function(resolve , reject) {resolve(2);}); }).then(function(val) {console.log(val);return new Promise(function(resolve , reject) {resolve(3);}); }).then(function(val) {console.log(val);return new Promise(function(resolve , reject) {resolve(4);}); }).then(function(val) {console.log(val); });
Promise實例的三種狀態:
每一個實例化的Promise都有三個狀態;pending(等待) ?rejected(拒絕) ?resolved(解決) ,默認的狀態為pending,如果執行了resolve(), 那么這個promise的狀態會變為resolve,如果執行了reject(), 那么這個promise的狀態就會變成rejected, 而且這些狀態是不可撤銷的,一經更改,不會再變了;
then方法:
promise有一個then方法,then方法接收兩個參數, 第一個為函數的成功回調, 第二個為函數的失敗回調:
var promise = new Promise(function(resolve , reject) {resolve(); //執行成功回調; }); console.log(0); promise.then(function(val) {console.log(1); }, function() {console.log("失敗"); }); console.log("2");
var promise = new Promise(function(resolve , reject) {reject(); }); console.log(0); promise.then(function(val) {console.log(1); }, function() {console.log("失敗"); }); console.log("2");
then方法每一次都是返回不同的Promise實例,then的第一個參數是成功回調, 這個成功回調的參數為: 上一個Promise實例執行resolve方法的參數;
一般來說, then方法會返回當前的promise, 如果在then方法里面return 一個新的Promise實例,那么此時的then返回的就是新的Promise實例, 利用這個特性,就可以實現多層回調;
new Promise(function(resolve , reject) {resolve(1); }).then(function(val) {console.log(val);return new Promise(function(resolve , reject) {resolve(2);}); }).then(function(val) {console.log(val);return new Promise(function(resolve , reject) {resolve(3);}); }).then(function(val) {console.log(val);return new Promise(function(resolve , reject) {resolve(4);}); }).then(function(val) {console.log(val); });
不管代碼是異步還是同步的, 都可以用Promise的then方法, 同步的代碼直接寫在then方法第一個參數, 把需要參數通過resolve傳給下一個then方法,
如果是異步的代碼, 就直接return一個Promise實例:
new Promise(function(resolve , reject) {resolve(1); }).then(function(val) {console.log(val);return 2; }).then(function(val) {console.log(val);return 3; }).then(function(val) {console.log(val);return new Promise(function(resolve,reject) {//異步操作些這里resolve(4);}); }).then(function(val) {console.log(val);return 5; }).then(function(val) {console.log(val); });
以上只是Promise的一些基礎知識, 還有一些其他的知識點, 因為能力有限不一一介紹了(Promise.resolve的不同參數, 與Generator一起使用, Promise的附加方法, 等等等等);