1

For example, I have pretty current versions of official Joyent NodeJS installed with of course the Google V8 JavaScript engine and also JXcore with the Mozilla SpiderMonkey JavaScript engine.

The former seems to come with native Promises support, the latter seems not to.

(And of course these are not the only two possible environments nodeJS code might run under.

How can my code test its environment to see whether it can use native Promises or not?

It's OK if it detects a proper polyfill as "native" in this case. But it shouldn't detect something like Q as native promises. (Or let me know if I'm wrong about this.)

3 Answers 3

2

To directly answer your question, use this to detect the availability of ES6 promises:

typeof global.Promise === 'function'

Alternatively use a lightweight ES6 promise polyfill instead of relying on a larger partially-incompatible library.

With a polyfill you can just use the normal Promise API and simply remove the require once it's no longer needed — no refactor necessary.


A longer but trustworthier alternative is something like what this package uses:

  global.Promise && Object.prototype.toString.call(global.Promise.resolve()) === '[object Promise]')
1

Well, you can use a package that uses native promises if they're available and if they're not it shims them.

Alternatively, since it's the server, you might be better off using a compatible userland library until all your environments support native promises.

Note that jxcore does not support some standard NodeJS promise features like unhandledRejection that userland polyfills and libraries support.

As for detecting native promises - it can be hard across environments. Technically you could check if there is a global Promise object as the first line of code in your program but that's messy compared to the alternative of just using a compatible faster userland library.

1

This might do it:

Promise.resolve() instanceof Promise

From comments to this other answer, it seems this only returns true for native ES6 promises.

This solution would likely reject a polyfill however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.