Promise.race() // 競速,完成一個即可進階進階promises 的奇妙在於給予我們以前的 return 與 throw,每個 Promise 都會提供一個 then() 函數,和一個 catch(),實際上是 then(null, ...) 函數,
omePromise().then(functoin(){ // do something });我們可以做三件事,
1. return 另一個 promise2. 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. bindomethingAsync().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;});然而,這有非常多的區別,
- 你必須先聲明,有浪費資源和記憶體泄露的風險
- 不能用於放在一個運算式的上下文中
- 效率更低
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 永遠不會 fulfilled11. .map(Function mapper [, Object options])用於處理一個數組,或者 promise 數組,
Option: concurrency 並發現
map(..., {concurrency: 1});
以下為不限制並發數量,讀書檔案資訊
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 1reading files 35ms$ sync && echo 3 > /proc/sys/vm/drop_caches$ node test.js Infinityreading files: 9ms11. .reduce(Function reducer [, dynamic initialValue]) -> PromisePromise.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
- .delay(int ms) -> Promise
- .timeout(int ms [, String message]) -> Promise
Promise 的實現
- q
- bluebird
- co
- when
ASYNCasync 函數與 Promise、Generator 函數一樣,是用來取代回呼函數、解決非同步作業的一種方法。它本質上是 Generator 函數的文法糖。async 函數並不屬於 ES6,而是被列入了 ES7。