本文根据 Devhints / bluebird.js 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2017-09-08。
另请参阅
另请参阅 Promise 速查表 以及 Bluebird.js API (github.com).
示例
promise
.then(okFn, errFn)
.spread(okFn, errFn) // *
.catch(errFn)
.catch(TypeError, errFn) // *
.finally(fn)
.map(function (e) { ··· }) // *
.each(function (e) { ··· }) // *
标记为 * 的内容属于非标准 Promise API,仅在使用 Bluebird Promise 时有效。
多个返回值
.then(function () {
return [ 'abc', 'def' ]
})
.spread(function (abc, def) {
···
})
多个 Promise
Promise.join(
getPictures(),
getMessages(),
getTweets(),
function (pics, msgs, tweets) {
return ···
}
)
使用 Promise.join
多个 Promise(数组)
- Promise.all([p]) - 期望全部成功
- Promise.some([p], count) - 期望
count成功 - Promise.any([p]) - 等同于
some([p], 1) - Promise.race([p], count) - 请改用
.any替代 - Promise.map([p], fn, options) - 支持并发
Promise.all([ promise1, promise2 ])
.then(results => {
results[0]
results[1]
})
// succeeds if one succeeds first
Promise.any(promises)
.then(results => {
})
Promise.map(urls, url => fetch(url))
.then(···)
使用 Promise.map 用于将一组值“Promise 化”(转换为 Promise)。
对象
Promise.props({
photos: get('photos'),
posts: get('posts')
})
.then(res => {
res.photos
res.posts
})
使用 Promise.props.
Promise 链
function getPhotos() {
return Promise.try(() => {
if (err) throw new Error("boo")
return result
})
}
getPhotos().then(···)
使用 Promise.try.
Node 风格函数
var readFile = Promise.promisify(fs.readFile)
var fs = Promise.promisifyAll(require('fs'))
参见 Promise 化(Promisification).
返回 Promise 的方法
User.login = Promise.method((email, password) => {
if (!valid)
throw new Error("Email not valid")
return /* promise */
})
参见 Promise.method.
生成器(Generators)
User.login = Promise.coroutine(function* (email, password) {
let user = yield User.find({email: email}).fetch()
return user
})