Overriding Promise implementation to Bluebird.Promise

118 views Asked by At

I've got a scenario where promise will be undefined for some remote executions of a code base. Locally, it's running Node. Remotely, its running another runtime that doesn't have Promises. Bluebird works fine, but I'd like to override Promise for all files if it is undefined.

Something like:

import { Promise as BlueBirdPromise } from 'bluebird';

if (!Promise) {
    Promise = BlueBirdPromise;
    Promise.setScheduler((fn: any) => {
        setTimeout(fn, 0);
    });
}

The above code doesn't work as Promise and BlueBirdPromise are different types. I believe Promise is an interface in TS.

Is there a clean way to do this?

Example:

import { Promise as BlueBirdPromise } from 'bluebird';

BlueBirdPromise.setScheduler((fn: any) => {
    setTimeout(fn, 0);
});
// eslint-disable-next-line
Promise = BlueBirdPromise;

Error:

polyfills.ts:13:1 - error TS2741: Property '[Symbol.species]' is missing in type 'typeof Bluebird' but required in type 'PromiseConstructor'.
1

There are 1 answers

2
Mmm Donuts On

We can accomplish this by overriding the Promise definition bound to the global object. This is done in the index.js file before any main code is executed.

Locally, Visual Studio Code will recognize Promise as its default type. However, when executed, this block will override the default Promise definition with that provided by Bluebird.

In this way, any use of Promise will use Bluebird over Node's definition. Or, in the case of the remote runtime not being node, provide an implementation where there is none.

import { Promise as BlueBirdPromise } from 'bluebird';

BlueBirdPromise.setScheduler((fn: any) => {
    setTimeout(fn, 0);
});

global.Promise = <any>BlueBirdPromise;