[TOC]
首先 我們需要知道 Promise 是 什么東西,為什么需要它!
對于前端 異步的概念,同學們都應該有過這樣的經歷,Ajax 的 `success /error` 回調,這樣的方式算是最早的異步回調了。對于回調(callback)有時候是令人反感的,比如當你陷入 回調地獄 時。
[原生 Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) 是在 ES2015 對 JavaScript 做出最大的改變。它的出現消除了采用 callback 機制的很多潛在問題,并允許我們采用近乎同步的邏輯去寫異步代碼。
可以說 promises 和?[generators](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/function%2a),代表了異步編程的新標準。
## Promise A+ 規范
* 官方英文地址:[https://promisesaplus.com/](https://promisesaplus.com/)
* 中文翻譯可參考:[http://malcolmyu.github.io/malnote/2015/06/12/Promises-A-Plus/](http://malcolmyu.github.io/malnote/2015/06/12/Promises-A-Plus/)
# 實現過程
Promise 設計模式原理及在 ES6 中的應用,手寫一個符合 Promise A+規范的 Promise 實現
# promise
```
function _Promise(fn) {
var self = this;
this.state = 'pending';
this.value = null;
this.callbacks = [];
this.then = function(onFulfilled, onRejected) {
// 返回一個新的Promise對象
return new _Promise(function(resolve, reject) {
handleCallback({
onFulfilled: onFulfilled || null,
onRejected: onRejected || null,
resolve: resolve,
reject: reject
})
})
}
function handleCallback(callback) {
if(self.state === 'pending') {
self.callbacks.push(callback);
return;
}
var cb = self.state === 'fulfilled' ? callback.onFulfilled : callback.onRejected;
if(cb === null) {
cb = self.state === 'fulfilled' ? callback.resolve : callback.reject;
cb(self.value);
return;
}
// 加入try-catch防止執行回調出錯
try {
var res = cb(self.value);
callback.resolve(res);
}catch(e) {
callback.reject(e);
}
}
function resolve(endValue) {
if(endValue && (typeof endValue === 'object') && typeof endValue.then === 'function') {
endValue.then(resolve, reject);
return;
}
self.state = 'fulfilled';
self.value = endValue;
console.log("set:" + self.callbacks.length);
excute();
}
function reject(reason) {
self.state = 'rejected';
self.value = reason;
excute();
}
function excute() {
// 讓所有回調函數進入下一個事件循環執行
setTimeout(function(){
self.callbacks.forEach(function(callback) {
handleCallback(callback);
})
},0);
}
fn(resolve, reject)
}
// 測試代碼:
var a = new _Promise( function(resolve) {
resolve(1);
})
a.then(x => {
return new _Promise(function (resolve) {
setTimeout(( )=> {
resolve(x+1)
console.log(x);
}, 2000)
})
}).then(x => {
return new _Promise(function (resolve) {
setTimeout(() => {
resolve(x+1)
console.log(x);
}, 2000)
})
}).then( x => console.log(x) )
```
* Promise.all
* Promise.race
* Promise 并行限制
> [promise-polyfill](https://github.com/taylorhakes/promise-polyfill/)
# 參考
[q](https://github.com/kriskowal/q)
[Promise 測試](https://github.com/whu-luojian/Promise.git)
[promisejs - Implementing](https://www.promisejs.org/implementing/)
[Promises 講解](https://www.cnblogs.com/superAnny/p/7622893.html)
# 附錄
[手寫 Promise 所有方法實現](https://www.jianshu.com/p/5119e01a036f)
[Promise/Generator/Co](https://www.cnblogs.com/JoeChan/p/4943384.html)
[常見Promise面試題](https://blog.csdn.net/weixin_34090562/article/details/88672431)
[Promise鏈式調用 終止或取消](https://www.cnblogs.com/gqx-html/p/10967412.html)
- 修仙之路
- 基礎原理篇
- JS和Node.js事件環機制剖析
- 一圖理解原型鏈
- 手寫篇
- 基礎手寫
- 手寫實現 Promise A+ 類庫
- 手寫 CommonJS
- 手寫 Express 框架
- 手寫 React Router 4.0
- 手寫虛擬 DOM 和 DOM-Diff
- 手寫 Webpack 實現
- 手寫一個 MVVM 類庫
- 手寫一個 Vue-cli 腳手架
- 手寫 JWT 類庫
- 手寫 Mobx 類庫
- 手寫前端性能和錯誤監控框架
- 手寫 Vue 路由
- 手寫 Vuex 實現
- 手寫 redux 狀態容器
- 手寫 throttle 和 debounce
- Node 高級
- Mongodb
- 安全測試篇
- CSRF原理實現
- XSS原理實現
- 九種跨域方法全解析
- 編寫單元測試
- 爬蟲篇
- 使用puppeteer破解滑動驗證碼
- 工程篇
- 使用AST語法樹手工轉譯ES6代碼
- 編寫自己的webpack插件
- 實戰篇
- webpack4.0 實戰
- Canvas+Websocket 實現彈幕
- canvas 動效
- SVG 動效
- CSS3 實現 Apple Watch 中的呼吸燈效果
- CSS3 實現動態氣泡屏保效果
- 算法篇
- 基礎知識
- 服務器端
- 分布式架構中的冪等性
- TCP/UDP
- Docker
- V8
- 動畫篇
- 貝塞爾曲線
- requestAnimationFrame
- 框架篇
- 隨記