将承诺转换为蓝鸟

时间:2015-06-15 18:24:31

标签: javascript node.js promise bluebird

我找到了一个使用promises的现有库,但是它没有使用bluebird。库函数没有提供bluebird与.map().tap()相同的所有额外功能。我如何将“正常”或“非蓝鸟”的承诺转换为蓝鸟承诺,蓝鸟提供的所有额外功能?

我尝试在Promise.promisifyPromise.resolve中包装现有的承诺,似乎都没有效果。

5 个答案:

答案 0 :(得分:71)

使用Promise.resolve - 它将采取任何可能的方式,如来自其他实现的承诺,并将其同化为Bluebird承诺。

请记住,the term "resolve"可能会产生误导,但这并不意味着与“履行”相同,但也可以遵循另一个承诺并接受其结果。

答案 1 :(得分:15)

如果您想将承诺转换为蓝鸟承诺,请不解决任何问题并返回customPromise,然后您就可以访问链中的所有蓝鸟自定义方法。

Promise.resolve().then(function(){
  return customPromise()
})

或者

Promise.resolve(customPromise())

答案 2 :(得分:1)

使用Bluebird的Promise.method

const Promise = require('bluebird');

const fn = async function() { return 'tapped!' };

bluebirdFn = Promise.method(fn);

bluebirdFn().tap(console.log) // tapped!
fn().tap(console.log) // error

答案 3 :(得分:0)

我使用Bluebird.resolve()方法将本机js promise转换为bluebird promise。

public getBatched(query: QueryBuilder | Raw): Bluebird<any> {
  return Bluebird.resolve(this.cache.getBatched(query));
}

答案 4 :(得分:0)

使用to-bluebird

const toBluebird = require("to-bluebird");

const es6Promise = new Promise(resolve => resolve("Hello World!")); // Regular native promise.
const bluebirdPromise = toBluebird(es6Promise); // Bluebird promise.

本地替代项:

在ECMAScript中:

import {resolve as toBluebird} from "bluebird"

在CommonJS中:

const {resolve: toBluebird} = require("bluebird")

用法:

const regularPromise = new Promise((resolve) => {
    resolve("Hello World!") // Resolve with "Hello World!"
})

const bluebirdPromise = toBluebird(regularPromise) // Convert to Bluebird promise

bluebirdPromise.then(val => console.log(val)) // Will log "Hello World!"