bluebird(Promise/A+)介紹

kdwh0504 8年前發布 | 18K 次閱讀 Prototype JavaScript開發

來自: http://giscafer.com/2016/02/04/bluebird-api-study/

Promises/A+規范

Promise

是一個擁有 then 方法的對象或函數,起行為符合本規范;

thenable

是一個定義了 then 方法的對象或函數,即 擁有then方法 ;

詳情介紹見文章 《Promises/A+規范》

bluebird

之前做node.js項目的時候一直使用樸靈的 eventproxy 來處理異步或者回調, eventproxy 采用的是事件機制,使用也挺方便。

現在也了解一下備受歡迎的 bluebird —— 官網 ,bb的API文檔很全很詳細。

.promisifyAll

官方API說明:

Promisifies the entire object by going through the object’s properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name suffixed with suffix (default is “Async”). Any class properties of the object (which is the case for the main export of many modules) are also promisified, both static and instance methods. Class property is a property with a function value that has a non-empty .prototype object. Returns the input object.

大概意思就是, Promise.promisifyAll 方法接收一個對象,會遍歷對象中的方法并克隆該方法并在其后加上 Async 字符。也就是說會多出一樣的方法,只不過都帶 Async (異步)的后綴。如果想將對象原型鏈上的方法也加上的話,則傳入對象的原型即可,例如 Promise.promisifyAll(obj.prototype) ,返回的是該對象。

.then

類似原生Promise/A+規范的then方法:

.then(

[function(any value) fulfilledHandler],

[function(any error) rejectedHandler]

) -> Promise

例子:(then和promisifyAll的使用)

 var Promise=require('bluebird');
var fs=Promise.promisifyAll(require('fs'));
var onFulfilled=function(data){
       console.log(data)
}
var onRejected=function(e){
    console.log('報錯啦--',e)
}
fs.readFileAsync('package.json', "utf8").then(onFulfilled,onRejected);

.catch

更方便的是, bluebird 提供了 .catch 方法,可以在”鏈式”的操作上捕獲異常,如上邊的例子可以改寫為如下方式:

 fs.readFileAsync('package.json', "utf8").then(function(data){//只需要關注成功的時候
    console.log(data);
}).catch(function(err){//輕松處理所有出現的異常
    console.log(err);
});

此外,還可以區別捕獲不同的異常,分別處理,只需要指定異常的類型(如 TypeError , ReferenceError , NetworkError 等)即可(和java的異常類型處理類似吧?)

例子1,區分不同錯誤類型捕捉:

somePromise.then(function() {
    return a.b.c.d();
}).catch(TypeError, ReferenceError, function(e) {
    //程序異常捕獲
}).catch(NetworkError, TimeoutError, function(e) {
    //網絡異常捕獲
}).catch(function(e) {
    //捕獲所有其他異常
});

例子2,捕捉找不到文件報錯:

fs.readFileAsync('package.jsn', "utf8").then(function (data) {
    console.log(data);
}).catch({ code: 'ENOENT' }, function (e) {
    console.log("file not found: " + e.path);
});

集合相關的方法

.all 方法可以處理一個數組內的所有方法,處理完畢返回信息,如例子異步創建10個文件后,返回成功信息:

var files = [];
for (var i = 0; i < 10; ++i) {
    files.push(fs.writeFileAsync("file-" + i + ".txt", "", "utf-8"));
}
Promise.all(files).then(function() {
    console.log("all the files were created");
});

還有其他好用的方法,需要的時候去了解一下API文檔,根據實際情況使用即可。

 本文由用戶 kdwh0504 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!