Coder Social home page Coder Social logo

rtsao / browser-unhandled-rejection Goto Github PK

View Code? Open in Web Editor NEW
28.0 5.0 4.0 14 KB

A ponyfill/polyfill for browser Promise unhandledrejection events

License: MIT License

JavaScript 100.00%
unhandled-rejection promise polyfill unhandledrejection ponyfill

browser-unhandled-rejection's Introduction

browser-unhandled-rejection

build status dependencies status npm version

A ponyfill/polyfill for browser Promise unhandledrejection events.

See: https://www.chromestatus.com/features/4805872211460096

sauce labs test status

Install

npm i browser-unhandled-rejection

or

yarn add browser-unhandled-rejection

Usage

Automatic polyfill

This automatically applies the polyfill to the global Promise object if it is needed.

import {auto} from 'browser-unhandled-rejection';

auto(); // Applies polyfill if necessary to window.Promise

Manual polyfill

The following snippet is equivalent to auto():

import {polyfill} from 'browser-unhandled-rejection';

if (typeof PromiseRejectionEvent !== 'undefined') {
  polyfill(); // Polyfills window.Promise
}

Ponyfill

This may may useful if you don't want to mutate window.Promise:

import MyPromise from 'browser-unhandled-rejection';

window.addEventListener('unhandledrejection', () => {
  console.log('unhandledrejection was triggered');
});

MyPromise.reject('will trigger unhandledrejection event');

new MyPromise((resolve, reject) => {
  reject('will also trigger unhandledrejection event');
});

browser-unhandled-rejection's People

Contributors

cognitom avatar lhorie avatar rtsao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

browser-unhandled-rejection's Issues

Polyfill does not handle returned rejections properly

test(`does not trigger event for recovered downstream 2 (${name})`, t => {
    t.plan(1);
    let count = 0;
    const reason = 'rejection';
    const listener = (e) => {
      count++;
    }
    window.addEventListener('unhandledrejection', listener);

    const promise = MyPromise.resolve().then(() => {
      return MyPromise.reject(reason);
    }).catch(() => {}).then(() => {});

    macrotask(() => {
      t.equal(count, 0, 'handler is not called');
      window.removeEventListener('unhandledrejection', listener);
    });
  });

The above test case will trigger an unhandledrejection even though a catch is present. The reason is that the inner MyPromise.reject doesn't have any chained promises.

Native subclassing and performance

I did a benchmark of various Promise subclassing methods.

Native ES6 subclassing will be smaller over the wire and (in some browsers) has somewhat better runtime performance. That said, there's some issues:

  1. Using ES6 class syntax in browsers that don't support it will raise a SyntaxError. This necessitates conditional script loading (or eval), which takes effort to set up by consumers of this module.
  2. Reflect.construct could be used as an alternative, but new.target will also raise a SyntaxError in browsers that don't support it. We could forego new.target, but then nobody will be able to subclass our polyfilled Promise.

For these reasons, this package will use ES5 subclassing. It's also faster in Firefox in my testing.

Allow for arbitrary unhandled rejection side effects

Right now this package is opinionated in that it dispatches unhandledrejection events.

Others may want to call window.onunhandledrejection. Or others may want to do something else entirely.

This package should allow folks to construct their own polyfill with their own side effects. This will probably only require a minor restructuring of the existing code.

Sorry,may I ask why after promise.then run, promise._hasDownstreams === undefined

if (promise._hasDownstreams === undefined) {

Here is my demo:

new InstrumentedPromise ((resolve, reject) => {
    reject('will also trigger unhandledrejection event');
  }).then(()=>{console.log(1)});

I test the code , the result is below:
image

You can see the first InstrumentedPromise run, the promise._hasDownstreams === true;
But the then function run ,the promise._hasDownstreams === undefined;

I'm very confused, could you tell my the reason, thanks very much.

Event is not triggered when Promise resolver throws

Steps to reproduce

Run polyfill in environment that natively supports unhandledrejection event (tested in Chrome 65).

Sample code

window.addEventListener('unhandledrejection', (e) => {
	if (e instanceof PromiseRejectionEvent) {
		console.log('native unhandledrejection', e.reason)
	} else {
		console.log('polyfilled unhandledrejection', e.reason)
	}
});
polyfill(); // force polyfill
// A
new Promise((resolve, reject) => reject('simple reject'));

// B
Promise.reject('static reject');

// C
new Promise((resolve, reject) => {
	throw new Error('throw');
});

Expected results

Both native and polyfill events fire consistently.

Actual results

Native unhandledrejection fires in all three cases.
Polyfilled unhandledrejection fires in cases A and B, but not C.

Also provide variant using native subclassing

For use cases where native subclassing of Promise is supported, it is preferable to use native subclassing instead of __proto__.

This package should provide this version as well.

Can't use it on node 10?

I did npm i browser-unhandled-rejection. And in my code:

import { auto } from 'browser-unhandled-rejection';

But my terminal is outputting Can't resolve 'browser-unhandled-rejection' error.

Using node 10.8.0 and npm 6.2.0.

Incompatible with Promise.prototype.finally

The native implementation of Promise.prototype.finally in Chrome doesn't work quite right with this polyfill.

When doing something like Promise.reject('test').finally(() => {}) the polyfill will not emit an unhandledrejection.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.