先放一張圖片感覺一下回調地獄promise
看起來是真的很讓人頭痛的東西異步
而如今我這裏使用promise對象來解決回調地獄函數
採用鏈式的 then,能夠指定一組按照次序調用的回調函數。spa
這時,前一個 then 裏的一個回調函數,返回的可能仍是一個 Promise
對象(即有異步操做),code
這時後一個回調函數,就會等待該 Promise
對象的狀態發生變化,纔會被調用。對象
由此實現異步操做按照次序執行。blog
var sayhello = function (name) { return new Promise(function (resolve, reject) { setTimeout(function () { console.log(name); resolve(); //在異步操做執行完後執行 resolve() 函數 }, 1000); }); } sayhello("first").then(function () { return sayhello("second"); //仍然返回一個 Promise 對象 }).then(function () { return sayhello("third"); }).then(function () { console.log('end'); }).catch(function (err) { console.log(err); }) //輸出:first second third end
上面代碼中,第一個 then 方法指定的回調函數,返回的是另外一個Promise
對象。圖片
這時,第二個then
方法指定的回調函數,就會等待這個新的Promise
對象狀態發生變化。回調函數
若是變爲resolved
,就繼續執行第二個 then 裏的回調函數it