前端神器--promise

Promise in js

回調函數真正的問題在於他剝奪了我們使用 return 和 throw 這些關鍵字的能力。而 Promise 很好地解決了這一切。

2015 年 6 月,ECMAScript 6 的正式版 終於發佈了。

ECMAScript 是 JavaScript 語言的國際標準,JavaScript 是 ECMAScript 的實現。ES6 的目標,是使得 JavaScript 語言可以用來編寫大型的複雜的應用程序,成爲企業級開發語言。

概念

ES6 原生提供了 Promise 對象。

所謂 Promise,就是一個對象,用來傳遞異步操作的消息。它代表了某個未來纔會知道結果的事件(通常是一個異步操作),並且這個事件提供統一的 API,可供進一步處理。

Promise 對象有以下兩個特點。

(1)對象的狀態不受外界影響。Promise 對象代表一個異步操作,有三種狀態:Pending(進行中)、Resolved(已完成,又稱 Fulfilled)和 Rejected(已失敗)。只有異步操作的結果,可以決定當前是哪一種狀態,任何其他操作都無法改變這個狀態。這也是 Promise 這個名字的由來,它的英語意思就是「承諾」,表示其他手段無法改變。

(2)一旦狀態改變,就不會再變,任何時候都可以得到這個結果。Promise 對象的狀態改變,只有兩種可能:從 Pending 變爲 Resolved 和從 Pending 變爲 Rejected。只要這兩種情況發生,狀態就凝固了,不會再變了,會一直保持這個結果。就算改變已經發生了,你再對 Promise 對象添加回調函數,也會立即得到這個結果。這與事件(Event)完全不同,事件的特點是,如果你錯過了它,再去監聽,是得不到結果的。

有了 Promise 對象,就可以將異步操作以同步操作的流程表達出來,避免了層層嵌套的回調函數。此外,Promise 對象提供統一的接口,使得控制異步操作更加容易。

Promise 也有一些缺點。首先,無法取消 Promise,一旦新建它就會立即執行,無法中途取消。其次,如果不設置回調函數,Promise 內部拋出的錯誤,不會反應到外部。第三,當處於 Pending 狀態時,無法得知目前進展到哪一個階段(剛剛開始還是即將完成)。

var promise = new Promise(function(resolve, reject) {
 if (/* 異步操作成功 */){
 resolve(value);
 } else {
 reject(error);
 }
});

promise.then(function(value) {
 // success
}, function(value) {
 // failure
});

Promise 構造函數接受一個函數作爲參數,該函數的兩個參數分別是 resolve 方法和 reject 方法。

如果異步操作成功,則用 resolve 方法將 Promise 對象的狀態,從「未完成」變爲「成功」(即從 pending 變爲 resolved);

如果異步操作失敗,則用 reject 方法將 Promise 對象的狀態,從「未完成」變爲「失敗」(即從 pending 變爲 rejected)。

基本的 api

  1. Promise.resolve()

  2. Promise.reject()

  3. Promise.prototype.then()

  4. Promise.prototype.catch()

  5. Promise.all() // 所有的完成

    var p = Promise.all([p1,p2,p3]);
    
  6. Promise.race() // 競速,完成一個即可

進階

promises 的奇妙在於給予我們以前的 return 與 throw,每個 Promise 都會提供一個 then() 函數,和一個 catch(),實際上是 then(null, ...) 函數,

    somePromise().then(functoin(){
        // do something
    });

我們可以做三件事,
1. return 另一個 promise
2. return 一個同步的值 (或者 undefined)
3. throw 一個同步異常 throw new Eror('');

1. 封裝同步與異步代碼

```
new Promise(function (resolve, reject) {
resolve(someValue);
});
```
寫成

```
Promise.resolve(someValue);
```

2. 捕獲同步異常

 new Promise(function (resolve, reject) {
 throw new Error('悲劇了,又出 bug 了');
 }).catch(function(err){
 console.log(err);
 });

如果是同步代碼,可以寫成

    Promise.reject(new Error("什麼鬼"));

3. 多個異常捕獲,更加精準的捕獲

somePromise.then(function() {
 return a.b.c.d();
}).catch(TypeError, function(e) {
 //If a is defined, will end up here because
 //it is a type error to reference property of undefined
}).catch(ReferenceError, function(e) {
 //Will end up here if a wasn't defined at all
}).catch(function(e) {
 //Generic catch-the rest, error wasn't TypeError nor
 //ReferenceError
});

4. 獲取兩個 Promise 的返回值

1. .then 方式順序調用
2. 設定更高層的作用域
3. spread

5. finally

任何情況下都會執行的,一般寫在 catch 之後

6. bind

somethingAsync().bind({})
.spread(function (aValue, bValue) {
 this.aValue = aValue;
 this.bValue = bValue;
 return somethingElseAsync(aValue, bValue);
})
.then(function (cValue) {
    return this.aValue + this.bValue + cValue;
});

或者 你也可以這樣

var scope = {};
somethingAsync()
.spread(function (aValue, bValue) {
 scope.aValue = aValue;
 scope.bValue = bValue;
 return somethingElseAsync(aValue, bValue);
})
.then(function (cValue) {
 return scope.aValue + scope.bValue + cValue;
});

然而,這有非常多的區別,

  1. 你必須先聲明,有浪費資源和內存泄露的風險
  2. 不能用於放在一個表達式的上下文中
  3. 效率更低

7. all。非常用於於處理一個動態大小均勻的 Promise 列表

8. join。非常適用於處理多個分離的 Promise

```
var join = Promise.join;
join(getPictures(), getComments(), getTweets(),
function(pictures, comments, tweets) {
console.log("in total: " + pictures.length + comments.length + tweets.length);
});
```

9. props。處理一個 promise 的 map 集合。只有有一個失敗,所有的執行都結束

```
Promise.props({
pictures: getPictures(),
comments: getComments(),
tweets: getTweets()
}).then(function(result) {
console.log(result.tweets, result.pictures, result.comments);
});
```

10. any 、some、race

```
Promise.some([
ping("ns1.example.com"),
ping("ns2.example.com"),
ping("ns3.example.com"),
ping("ns4.example.com")
], 2).spread(function(first, second) {
console.log(first, second);
}).catch(AggregateError, function(err) {

err.forEach(function(e) {
console.error(e.stack);
});
});;
```
有可能,失敗的 promise 比較多,導致,Promsie 永遠不會 fulfilled

11. .map(Function mapper [, Object options])

用於處理一個數組,或者 promise 數組,

Option: concurrency 並發現

    map(..., {concurrency: 1});

以下爲不限制併發數量,讀書文件信息

var Promise = require("bluebird");
var join = Promise.join;
var fs = Promise.promisifyAll(require("fs"));
var concurrency = parseFloat(process.argv[2] || "Infinity");

var fileNames = ["file1.json", "file2.json"];
Promise.map(fileNames, function(fileName) {
 return fs.readFileAsync(fileName)
 .then(JSON.parse)
 .catch(SyntaxError, function(e) {
 e.fileName = fileName;
 throw e;
 })
}, {concurrency: concurrency}).then(function(parsedJSONs) {
 console.log(parsedJSONs);
}).catch(SyntaxError, function(e) {
 console.log("Invalid JSON in file " + e.fileName + ": " + e.message);
});

結果

$ sync && echo 3 > /proc/sys/vm/drop_caches
$ node test.js 1
reading files 35ms
$ sync && echo 3 > /proc/sys/vm/drop_caches
$ node test.js Infinity
reading files: 9ms

11. .reduce(Function reducer [, dynamic initialValue]) -> Promise

Promise.reduce(["file1.txt", "file2.txt", "file3.txt"], function(total, fileName) {
 return fs.readFileAsync(fileName, "utf8").then(function(contents) {
 return total + parseInt(contents, 10);
 });
}, 0).then(function(total) {
 //Total is 30
});

12. Time

  1. .delay(int ms) -> Promise
  2. .timeout(int ms [, String message]) -> Promise

Promise 的實現

  1. q
  2. bluebird
  3. co
  4. when

ASYNC

async 函數與 Promise、Generator 函數一樣,是用來取代回調函數、解決異步操作的一種方法。它本質上是 Generator 函數的語法糖。async 函數並不屬於 ES6,而是被列入了 ES7。

參考文獻(說是抄也可以的):

阮一峯的ES6 教程
關於promises,你理解了多少?
Bluebird 的官方文檔



作者:流星狂飆
鏈接:http://www.jianshu.com/p/063f7e490e9a
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。ise in js

回調函數真正的問題在於他剝奪了我們使用 return 和 throw 這些關鍵字的能力。而 Promise 很好地解決了這一切。

2015 年 6 月,ECMAScript 6 的正式版 終於發佈了。

ECMAScript 是 JavaScript 語言的國際標準,JavaScript 是 ECMAScript 的實現。ES6 的目標,是使得 JavaScript 語言可以用來編寫大型的複雜的應用程序,成爲企業級開發語言。

概念

ES6 原生提供了 Promise 對象。

所謂 Promise,就是一個對象,用來傳遞異步操作的消息。它代表了某個未來纔會知道結果的事件(通常是一個異步操作),並且這個事件提供統一的 API,可供進一步處理。

Promise 對象有以下兩個特點。

(1)對象的狀態不受外界影響。Promise 對象代表一個異步操作,有三種狀態:Pending(進行中)、Resolved(已完成,又稱 Fulfilled)和 Rejected(已失敗)。只有異步操作的結果,可以決定當前是哪一種狀態,任何其他操作都無法改變這個狀態。這也是 Promise 這個名字的由來,它的英語意思就是「承諾」,表示其他手段無法改變。

(2)一旦狀態改變,就不會再變,任何時候都可以得到這個結果。Promise 對象的狀態改變,只有兩種可能:從 Pending 變爲 Resolved 和從 Pending 變爲 Rejected。只要這兩種情況發生,狀態就凝固了,不會再變了,會一直保持這個結果。就算改變已經發生了,你再對 Promise 對象添加回調函數,也會立即得到這個結果。這與事件(Event)完全不同,事件的特點是,如果你錯過了它,再去監聽,是得不到結果的。

有了 Promise 對象,就可以將異步操作以同步操作的流程表達出來,避免了層層嵌套的回調函數。此外,Promise 對象提供統一的接口,使得控制異步操作更加容易。

Promise 也有一些缺點。首先,無法取消 Promise,一旦新建它就會立即執行,無法中途取消。其次,如果不設置回調函數,Promise 內部拋出的錯誤,不會反應到外部。第三,當處於 Pending 狀態時,無法得知目前進展到哪一個階段(剛剛開始還是即將完成)。

var promise = new Promise(function(resolve, reject) {
 if (/* 異步操作成功 */){
 resolve(value);
 } else {
 reject(error);
 }
});

promise.then(function(value) {
 // success
}, function(value) {
 // failure
});

Promise 構造函數接受一個函數作爲參數,該函數的兩個參數分別是 resolve 方法和 reject 方法。

如果異步操作成功,則用 resolve 方法將 Promise 對象的狀態,從「未完成」變爲「成功」(即從 pending 變爲 resolved);

如果異步操作失敗,則用 reject 方法將 Promise 對象的狀態,從「未完成」變爲「失敗」(即從 pending 變爲 rejected)。

基本的 api

  1. Promise.resolve()

  2. Promise.reject()

  3. Promise.prototype.then()

  4. Promise.prototype.catch()

  5. Promise.all() // 所有的完成

    var p = Promise.all([p1,p2,p3]);
    
  6. Promise.race() // 競速,完成一個即可

進階

promises 的奇妙在於給予我們以前的 return 與 throw,每個 Promise 都會提供一個 then() 函數,和一個 catch(),實際上是 then(null, ...) 函數,

    somePromise().then(functoin(){
        // do something
    });

我們可以做三件事,
1. return 另一個 promise
2. return 一個同步的值 (或者 undefined)
3. throw 一個同步異常 throw new Eror('');

1. 封裝同步與異步代碼

```
new Promise(function (resolve, reject) {
resolve(someValue);
});
```
寫成

```
Promise.resolve(someValue);
```

2. 捕獲同步異常

 new Promise(function (resolve, reject) {
 throw new Error('悲劇了,又出 bug 了');
 }).catch(function(err){
 console.log(err);
 });

如果是同步代碼,可以寫成

    Promise.reject(new Error("什麼鬼"));

3. 多個異常捕獲,更加精準的捕獲

somePromise.then(function() {
 return a.b.c.d();
}).catch(TypeError, function(e) {
 //If a is defined, will end up here because
 //it is a type error to reference property of undefined
}).catch(ReferenceError, function(e) {
 //Will end up here if a wasn't defined at all
}).catch(function(e) {
 //Generic catch-the rest, error wasn't TypeError nor
 //ReferenceError
});

4. 獲取兩個 Promise 的返回值

1. .then 方式順序調用
2. 設定更高層的作用域
3. spread

5. finally

任何情況下都會執行的,一般寫在 catch 之後

6. bind

somethingAsync().bind({})
.spread(function (aValue, bValue) {
 this.aValue = aValue;
 this.bValue = bValue;
 return somethingElseAsync(aValue, bValue);
})
.then(function (cValue) {
    return this.aValue + this.bValue + cValue;
});

或者 你也可以這樣

var scope = {};
somethingAsync()
.spread(function (aValue, bValue) {
 scope.aValue = aValue;
 scope.bValue = bValue;
 return somethingElseAsync(aValue, bValue);
})
.then(function (cValue) {
 return scope.aValue + scope.bValue + cValue;
});

然而,這有非常多的區別,

  1. 你必須先聲明,有浪費資源和內存泄露的風險
  2. 不能用於放在一個表達式的上下文中
  3. 效率更低

7. all。非常用於於處理一個動態大小均勻的 Promise 列表

8. join。非常適用於處理多個分離的 Promise

```
var join = Promise.join;
join(getPictures(), getComments(), getTweets(),
function(pictures, comments, tweets) {
console.log("in total: " + pictures.length + comments.length + tweets.length);
});
```

9. props。處理一個 promise 的 map 集合。只有有一個失敗,所有的執行都結束

```
Promise.props({
pictures: getPictures(),
comments: getComments(),
tweets: getTweets()
}).then(function(result) {
console.log(result.tweets, result.pictures, result.comments);
});
```

10. any 、some、race

```
Promise.some([
ping("ns1.example.com"),
ping("ns2.example.com"),
ping("ns3.example.com"),
ping("ns4.example.com")
], 2).spread(function(first, second) {
console.log(first, second);
}).catch(AggregateError, function(err) {

err.forEach(function(e) {
console.error(e.stack);
});
});;
```
有可能,失敗的 promise 比較多,導致,Promsie 永遠不會 fulfilled

11. .map(Function mapper [, Object options])

用於處理一個數組,或者 promise 數組,

Option: concurrency 並發現

    map(..., {concurrency: 1});

以下爲不限制併發數量,讀書文件信息

var Promise = require("bluebird");
var join = Promise.join;
var fs = Promise.promisifyAll(require("fs"));
var concurrency = parseFloat(process.argv[2] || "Infinity");

var fileNames = ["file1.json", "file2.json"];
Promise.map(fileNames, function(fileName) {
 return fs.readFileAsync(fileName)
 .then(JSON.parse)
 .catch(SyntaxError, function(e) {
 e.fileName = fileName;
 throw e;
 })
}, {concurrency: concurrency}).then(function(parsedJSONs) {
 console.log(parsedJSONs);
}).catch(SyntaxError, function(e) {
 console.log("Invalid JSON in file " + e.fileName + ": " + e.message);
});

結果

$ sync && echo 3 > /proc/sys/vm/drop_caches
$ node test.js 1
reading files 35ms
$ sync && echo 3 > /proc/sys/vm/drop_caches
$ node test.js Infinity
reading files: 9ms

11. .reduce(Function reducer [, dynamic initialValue]) -> Promise

Promise.reduce(["file1.txt", "file2.txt", "file3.txt"], function(total, fileName) {
 return fs.readFileAsync(fileName, "utf8").then(function(contents) {
 return total + parseInt(contents, 10);
 });
}, 0).then(function(total) {
 //Total is 30
});

12. Time

  1. .delay(int ms) -> Promise
  2. .timeout(int ms [, String message]) -> Promise

Promise 的實現

  1. q
  2. bluebird
  3. co
  4. when

ASYNC

async 函數與 Promise、Generator 函數一樣,是用來取代回調函數、解決異步操作的一種方法。它本質上是 Generator 函數的語法糖。async 函數並不屬於 ES6,而是被列入了 ES7。

參考文獻(說是抄也可以的):

阮一峯的ES6 教程
關於promises,你理解了多少?
Bluebird 的官方文檔



作者:流星狂飆
鏈接:http://www.jianshu.com/p/063f7e490e9a
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章