javascript 将承诺转换为蓝鸟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30852343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:47:57  来源:igfitidea点击:

Convert promise to bluebird

javascriptnode.jspromisebluebird

提问by ThomasReggi

I found an existing library that uses promises, however it doesn't use bluebird. The library functions don't come with all the extra features bluebird does like .map()or .tap(). How do I convert a "normal" or "non-bluebird" promise to a bluebird one, with all the extra features bluebird offers?

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

I tried wrapping the existing promise in Promise.promisifyand Promise.resolveand neither seemed to work.

我试过包装在现有的承诺Promise.promisify,并Promise.resolve和他们俩谁也没工作。

回答by Bergi

Use Promise.resolve- it will take any thenable, like a promise from some other implementation, and assimilate it into a Bluebird promise.

使用Promise.resolve- 它将接受任何 thenable,例如来自其他实现的承诺,并将其吸收到 Bluebird 承诺中。

Keep in mind that the term "resolve"can be misleading, it does not mean the same as "fulfill" but can also follow another promise and settle to its result.

请记住,“解决”一词可能具有误导性,它与“履行”的意思不同,但也可以遵循另一个承诺并接受其结果。

回答by ThomasReggi

If you want to convert the promise to a bluebird promise resolve nothing and return the customPromisethen you'll have access to all of bluebirds custom methods in the chain.

如果您想将承诺转换为 bluebird 承诺,什么都不解决并返回,customPromise那么您将可以访问链中的所有 bluebirds 自定义方法。

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

Or

或者

Promise.resolve(customPromise())

回答by richardpringle

Use Bluebird's Promise.method!

使用蓝鸟的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

回答by Richie Bendall

Using to-bluebird:

使用to-bluebird

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

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

Native alternative:

原生替代:

In ECMAScript:

在 ECMAScript 中:

import {resolve as toBluebird} from "bluebird"

In CommonJS:

在 CommonJS 中:

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

Usage:

用法:

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