Bluebird是nodejs最出名的Promise实现,除了实现标准的Promise规范之外,还提供了标准的包装方法,可以将nodejs回调风格的函数包装成Promise
Bluebird的使用
https://www.npmjs.com/package/bluebird
1 安装依赖
npm install -S bluebird
2 使用bluebird.promisifyAll()方法将nodejs回调风格的函数包装成Promise对象
bluebird.promisifyAll(target, options)
target
: 目标对象,如果是普通对象,则包装后生成的异步API只有该对象持有,如果是原型对象,则包装后生成的异步API被所有实例持有
options选项
:
- suffix:异步API方法名后缀,默认为Async,例如:fs.readFile()函数包装之后生成的API为fs.readFileAsync()
- multiArgs: 是否允许多个回调参数,默认为false,正常情况下,promise的then方法只接受一个参数,但是callback的形式,可以传多个参数,multiArgs设置为true的时候,bluebird会将所有的参数通过数组的形式传递给then方法
bluebird.promisifyAll只会给目标对象添加新的方法,原来的不受影响
使用bluebird.promisify包装之后,就不再传递回调函数了,而是使用then的方式来获取结果
看下面的例子:
const bluebird = require('bluebird')
const fs = require('fs')
bluebird.promisifyAll(fs)
fs.readFile('./data.log', {encoding: 'utf-8'}, (err, data) => {
if (err) {
throw new Error('error')
return
}
console.log(data)
})
fs.readFileAsync('./data.log', {encoding: 'utf-8'}).then(data => {
console.log(data)
}).catch(err => {
console.log(err)
})