"The Power of ES6 Promises in TypeScript and Harnessing the Strength of Bluebird Prom

I'm currently working on a nodejs/typescript 2 project that utilizes the es6-promise package from GitHub. However, I've decided to eliminate this dependency and target ES6 directly in typescript.

After removing the es6-promise package, I updated my tsconfig.json file to set the target as es6.

{
  "compilerOptions": {
    "target": "es6",
    // ...
  }
}

Some third-party packages rely on Bluebird promises, which are not compatible with the default ES6 promise. This issue has been documented on various GitHub posts:

This inconsistency is causing the following error:

TS2322: Type 'Bluebird' is not assignable to type 'Promise'. Property '[Symbol.toStringTag]' is missing in type 'Bluebird'.

There is another types package available on npm called @types/bluebird-global. In a blog post, it was recommended to use this package instead of @types/bluebird, but certain third-party packages (e.g., sequelize typings) reference bluebird and not bluebird-global, resulting in another error for the missing typings of bluebird.

What would be an effective solution to resolve this issue?

Answer №1

My situation involved

Encountered TS2322 error: Type 'Bluebird' is not compatible with type 'Promise'. Missing property '[Symbol.toStringTag]' in type 'Bluebird'.

During my search for a solution, I stumbled upon this discussion: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/10801

To summarize, here are the options:

  1. Add the following code to each of your .ts entry files to override the global promise:

    import * as Bluebird from 'bluebird';

    declare global { export interface Promise<T> extends Bluebird<T> {} }

Alternatively,

  1. Wrap all promises within a Bluebird promise constructor. This method might introduce some runtime overhead and is considered an anti-pattern on Bluebird's website.

On a side note, I personally had success with the first option while encountering challenges with the second one.

Answer №2

Bluebird does not have a [Symbol.toStringTag], making it incompatible. Bluebird's implementation differs from native Promise in areas such as scheduler and error handling. To handle this properly:

const promise: Promise<type> = Promise.resolve<type>(bluebirdPromise);

If runtime compatibility is not an issue, you can address this with type casting in a relatively type-safe manner:

const promise: Promise<type> = <Promise<type>><any><Bluebird<type>>bluebirdPromise;

or

const promise: Promise<type> = <Promise<type>><PromiseLike<type>>bluebirdPromise;

Answer №3

In order to prevent encountering this issue, I make sure to include the async keyword in the function that is responsible for returning a promise using Bluebird.

For instance:

async myAsyncFunction(items){
   return Bluebird.map( items, (item) => {
      ...
   })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Express and Node.js to encode an image file as base64 data

I need to convert an image file into base64 format in order to store it as a string in a mongoDB database. This is my current approach: router.post('/file_upload',function(req,res){ function base64_encode(file) { var bitmap = fs.readFile ...

I am currently in the process of cross-referencing the tags that have been retrieved with those that have been selected or created. If a tag does not exist

I have a collection of tags in an object, and I want to dynamically add new tags before submitting the form. Despite using vue watch, it doesn't seem to be working for me. Here is the code snippet: data() { return { blog: { blog_ti ...

Is Your Website Optimized for All Devices?

Creating this website was just a little project for me. I've been experimenting with different methods to ensure it's compatible with all devices and fits perfectly on each screen. Unfortunately, I'm pretty clueless when it comes to @media ...

Employing ng-style for establishing background when the value does not align

Greetings all! I am using ng-repeat to create a list of items within a ul element. Within the json data, there is a specific value that I want to highlight if it does not match a predefined string. Here's what I have so far: ng-style="{'backgro ...

Analyzing the differences in environment management between express and dotenv

Lately, I've noticed an abundance of tutorials and articles discussing NodeJS and the dotenv library. One common practice that keeps coming up is defining an ENV_MODE=development variable within the config.env file. However, it got me thinking - does ...

Extract and loop through JSON data containing various headers

Having no issues iterating through a simple JSON loop, however, the API I am currently utilizing returns a response with multiple headers. Despite my efforts in various methods to access the results objects, I still face some challenges. The response struc ...

How does the order of objects in an array change when using *ngFor in Angular with a .subscribe() method in Ionic 3?

As a newcomer to Ionic 3 & Angular, I encountered a challenge with the *ngFor and .subscribe() method. Please bear with me if this question seems simple. I attempted to understand the behavior of the http.get(..).map(..).subscribe() function when combined ...

The loop does not seem to be cycling through every item in the JSON dataset

In the JSON dataset provided, there seems to be an issue with the loop only iterating through the first pokemon, Bulbasaur. When typing in names of other pokemons such as "Ivysaur" or "Venusaur", it simply shows "Not found". Take a look at the code snipp ...

Prevent AngularJS from automatically inserting slashes in front of every single and double quote

When I bind HTML to a span tag, the content ends up having slashes before every single and double quote. <span ng-bind-html="qn.quest_text"></span> For example: Lorem Ipsum has been the industry's standard dummy text ever since the 1500 ...

Using ng-repeat to bind checkboxes to an object

I recently started using AngularJS and I'm attempting to bind the object "Optouts.Spouse" to checkboxes that are being ng-repeated from the Plans object. In my JS, I have: $scope.optouts = { spouse: {}, children: {} }; $scope.plans = {mec:true;anoth ...

Having trouble calculating the number of days between two dates at this moment

I'm working with a code snippet that involves comparing two dates – a specified date and the current date. However, when trying to calculate the difference in days between these dates, I keep getting either 0 or an unexpectedly large number like "31 ...

ExpressJS and NodeJS: Troubleshooting jQuery Integration Issues

Hey there, I'm diving into Express for the first time. I've been experimenting with sessions and ajax calls, but I've hit a roadblock. Every time I launch my app, my jquery seems to be failing for some unknown reason. Here's the snippet ...

Upload the PDF file along with other form data in a React application

I'm currently facing an issue with using formData for submitting a pdf file const [file,setFile] = useState() const [isFilePicked, setIsFilePicked] = useState(false); I have an input of type file <input accept=".pdf" type="file&quo ...

What measures can I take to block their access to a specific location?

Currently, I am utilizing /style to link the stylesheet style.css, and here is the corresponding code snippet: app.get("/style", (req, res) => res.sendFile(__dirname + "/assets/style.css")) To prevent unauthorized access to the /sty ...

React: The value selected in the <select> dropdown was passed as an [object Object]

I'm encountering an issue where I am attempting to pass an object that is being mapped through a combo-box. However, instead of passing the actual object, it is passing the value of [object Object]. When I console log the object, it displays the corre ...

A router that has numerous parameters will not function properly with express.static

I successfully created an express router with the parameter 'router.get('/add')' and it is working perfectly. However, when I added 'router.get('/edit/:id')', the express.static feature stopped working, causing issue ...

Sending information from one ajax request to anotherORTransferring

Apologies for not including code in this post as I am currently working on a project in a car without internet access. Thankfully, I am using the amazing Stack Exchange app. Currently, I am facing a challenge where I need to work with two separate API cal ...

In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with: export class UserListComponent implements OnInit, OnDestroy { private _subscriptions: Subscription; private _users: User[] = []; private _clickableUser: boolean = true; constructor( priv ...

Navigating the realm of JavaScript and managing the uncertainties of floating point precision

I am exploring the development of a browser multiplayer game utilizing rollback netcode that operates a deterministic simulation on the clients. I successfully prototyped the netcode in Flash, but encountered a floating point roadblock along the way. As f ...

Issue TS2305: The module "tls" does not have a member called 'TLSSocketOptions' available for export

Having trouble connecting to MongoDB in my Node.js project using the MongoDB drivers. I keep getting an error message that says "node_modules/mongodb/mongodb.ts34.d.ts:31:10 - error TS2305: Module 'tls' has no exported member 'TLSSocketOptio ...