【问题标题】:Convert promise to bluebird将承诺转换为蓝鸟
【发布时间】:2018-01-10 02:36:14
【问题描述】:

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

我尝试将现有的承诺包装在 Promise.promisifyPromise.resolve 中,但似乎都不起作用。

【问题讨论】:

  • 更新并找到了正确答案,这并不是特别简单,因为我的承诺链顶部总是有一个蓝鸟承诺。

标签: javascript node.js promise bluebird


【解决方案1】:

使用Promise.resolve - 它将接受任何thenable,就像来自其他实现的promise,并将其同化为Bluebird promise。

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

【讨论】:

  • @danfromisrael Promise.resolve 也会接受被拒绝的承诺并同样吸收它们。
  • 示例:var Promise = require("bluebird"); Promise.resolve(nonBluebirdPromise).reflect() Reflect 只是一个 bluebird 函数,否则将无法使用
  • @danfromisrael "resolve" 可能会产生误导。这并不意味着“成功”。 “解决” Promise 意味着等待它成功或失败。所以 Promise.resolve 只是解决/解析传递的 Promise 的值状态,无论是成功还是错误。
  • @d512 请不要将 CodeBling 的评论复制到我的回答中,尤其是在没有署名的情况下
  • 因为,呃,plagiarism?支持他的 cmets 就足够了。
【解决方案2】:

如果您想将 Promise 转换为 bluebird Promise,则不解决任何问题并返回 customPromise,那么您将可以访问链中的所有 bluebirds 自定义方法。

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

或者

Promise.resolve(customPromise())

【讨论】:

  • Promise.resolve(customPromise()) 应该足够了,不需要额外的.then
  • 如果您需要防止同步异常,@LeonidBeschastny a Promise.try 也可以使用
【解决方案3】:

使用 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

【讨论】:

    【解决方案4】:

    使用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!"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 2014-02-13
      • 2014-11-06
      相关资源
      最近更新 更多