我可以通过bluebird在node的全局范围内的实现来覆盖ES6的承诺吗?

时间:2023-01-15 20:39:24

I want to use bluebird's implementation of the Promise/A+ open standard and override native ES6 Promises. I also want the bluebird implementation to be available everywhere in my subsequently imported modules without having to require it in every single one of them. Bluebird's Getting started page tells me to:

我想使用bluebird实现的Promise/A+ open标准并覆盖本机ES6承诺。我还想让bluebird实现在我随后导入的模块中随处可用,而无需在每个模块中都需要它。《蓝鸟入门》页面告诉我:

var Promise = require("bluebird");

, which results in overriding the native Promise element. Because bluebird is a superset of the spec, it will not break existing code and is thus supposed to be safe to use.

,这导致重写本机Promise元素。因为bluebird是规范的超集,它不会破坏现有的代码,因此应该是安全的。

However, because I know it's considered bad practice to:

然而,因为我知道这被认为是不好的做法:

  1. extend or replace language natives, and
  2. 扩展或替换母语,并
  3. define globals for use in a require chain that depends on it
  4. 定义在依赖于它的需求链中使用的全局变量

, I'm wary when I want to include this in the base script of a node app:

,当我想要在节点应用程序的基本脚本中包含这个内容时,我会很谨慎:

import Promise from 'bluebird';
global.Promise = Promise;

Is this a bad practice? Should I stick to importing bluebird in every single file?

这种做法不好吗?我应该坚持在每个文件中导入bluebird吗?

1 个解决方案

#1


16  

I have done this hundreds of times in my code over the last 4 years and so have plenty others among the 10 million monthly downloads.

在过去的4年里,我在我的代码中已经做了数百次这样的操作,所以在每月1000万次的下载中还有很多其他的操作。

It is officially supported to swap the native implementation with bluebird.

官方支持使用bluebird交换本机实现。

I do

我做

const Promise = require("bluebird");

On a per-file basis. Note that usuaslly you can promisify your APIs once and then generally avoid calling Promise - calling at most .resolve.

在上面的基础上。请注意,通常情况下,您可以对api进行一次宣传,然后通常避免调用Promise—最多调用.resolve。

#1


16  

I have done this hundreds of times in my code over the last 4 years and so have plenty others among the 10 million monthly downloads.

在过去的4年里,我在我的代码中已经做了数百次这样的操作,所以在每月1000万次的下载中还有很多其他的操作。

It is officially supported to swap the native implementation with bluebird.

官方支持使用bluebird交换本机实现。

I do

我做

const Promise = require("bluebird");

On a per-file basis. Note that usuaslly you can promisify your APIs once and then generally avoid calling Promise - calling at most .resolve.

在上面的基础上。请注意,通常情况下,您可以对api进行一次宣传,然后通常避免调用Promise—最多调用.resolve。