Bluebird中Promise模式使用

bluebird logo
Bluebird是一个高性能全功能的Promise库,主要有以下特性:

  • 实现了Promises A+规范
  • 同步检查(promise状态,返回值,失败原因)
  • 并发调用(调用多个异步处理)
  • 异步模型转化到Promise模式
  • 使用通过并行使用Python/C#进行资源管理的取消和超时
  • 并行的C#异步和等待
  • 试用的工具方法,如:
    .bind()
    .call()
    Promise.join()…
  • 调试解决方案和合理的默认值
  • 优越的性能表现

bluebird支持node.js和浏览器端

node.js

1
npm install bluebird

然后

1
var Promise = require("bluebird");

浏览器端支持(ES5)

浏览器支持

可见对于IE必须是IE9和以上

用法:

下载:bluebird.jsbluebird.min.js

以解析一个json文件为例

1
2
3
4
5
6
7
8
9
fs.readFileAsync("file.json").then(JSON.parse).then(function(val) {
console.log(val.success);
})
.catch(SyntaxError, function(e) {
console.error("invalid json in file");
})
.catch(function(e) {
console.error("unable to read file");
});

具体需要看详细的可以查看官方github