Git Product home page Git Product logo

promise.prototype.finally's Introduction

promise.prototype.finally Version Badge

github actions coverage dependency status dev dependency status License Downloads

npm badge

ES Proposal spec-compliant shim for Promise.prototype.finally. Invoke its "shim" method to shim Promise.prototype.finally if it is unavailable or noncompliant. Note: a global Promise must already exist: the es6-shim is recommended.

This package implements the es-shim API interface. It works in an ES3-supported environment that has Promise available globally, and complies with the proposed spec.

Most common usage:

var assert = require('assert');
var promiseFinally = require('promise.prototype.finally');

var resolved = Promise.resolve(42);
var rejected = Promise.reject(-1);

promiseFinally(resolved, function () {
	assert.equal(arguments.length, 0);

	return Promise.resolve(true);
}).then(function (x) {
	assert.equal(x, 42);
});

promiseFinally(rejected, function () {
	assert.equal(arguments.length, 0);
}).catch(function (e) {
	assert.equal(e, -1);
});

promiseFinally(rejected, function () {
	assert.equal(arguments.length, 0);

	throw false;
}).catch(function (e) {
	assert.equal(e, false);
});

promiseFinally.shim(); // will be a no-op if not needed

resolved.finally(function () {
	assert.equal(arguments.length, 0);

	return Promise.resolve(true);
}).then(function (x) {
	assert.equal(x, 42);
});

rejected.finally(function () {
	assert.equal(arguments.length, 0);
}).catch(function (e) {
	assert.equal(e, -1);
});

rejected.finally(function () {
	assert.equal(arguments.length, 0);

	throw false;
}).catch(function (e) {
	assert.equal(e, false);
});

Tests

Simply clone the repo, npm install, and run npm test

Thanks

Huge thanks go out to @matthew-andrews, who provided the npm package name for v2 of this module. v1 is both in the original repo and preserved in a branch

promise.prototype.finally's People

Contributors

ljharb avatar nolde 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

promise.prototype.finally's Issues

Angular-CLI Usage?

Where do I need to call shim() ?

I'm assuming it needs to go in main.ts:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { shim } from 'promise.prototype.finally';

shim();

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

however, the TypeScript compiler complains about not finding the 'finally' property in implementations: error TS2339: Property 'finally' does not exist on type 'Promise<void>'

What am I doing wrong?

Consider removing es-abstract dependency to reduce size considerably

Just looked at the bundle size through source-map-explorer and observed that 'es-abstract' required by 'Promise.prototype.finally' takes 43Kb of minified bundle size 13,9% of total.

This package uses few es-abstract methods and removing its reliance on it, would decrease the size considerably.

If you think is doable, i can prepare a PR.

shim() not shimming on karma/phantomJS

For some weird reason the shim() isn't able to shim the global Promise on karma with the phantomJS driver (the main app works fine, and the jasmine client version of the specs work fine on other browsers).

When debugging I see the shim hitting define-property here:

if (supportsDescriptors) {
 // it actually fires this
  Object.defineProperty(object, name, {
    configurable: true,
    enumerable: false,
    value: value,
    writable: true
  });
} else { ... }

but then

require('promise.prototype.finally').shim()
console.log(Promise.prototype.finally) // logs undefined

Now if I pass the Promise object to the shim and change the library function signature accordingly it works

// shim.js
...
module.exports = function shimPromiseFinally(obj) {
	obj = obj || Promise;
	requirePromise();

	var polyfill = getPolyfill();
	define(obj.prototype, { 'finally': polyfill }, {
		'finally': function testFinally() {
			return obj.prototype['finally'] !== polyfill;
		}
	});
	return polyfill;
};
...


// karma.entry.js
require('promise.prototype.finally').shim(Promise)
console.log(Promise.prototype.finally) // logs the polyfill, it works!

I can submit a PR if you think this is something you want to add (I've seen other shimming libs do this too, perhaps this is a common issue)


PS: for anyone wondering this is my quick fix for now:

const finallyPolyfill = require('promise.prototype.finally').shim()

// Make sure we're shimming promise.finally.
// (auto .shim() doesn't work in karma for some reason)
if (!Promise.prototype.finally) { Promise.prototype.finally = finallyPolyfill }

Redundant unhandledrejection events

Hi,

if you'll write something like this:

Promise.reject('reject')
  .finally(() => console.warn('finally'))
  .catch(() => console.warn('catch'));

You'll get the following output:

finally
catch
Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: undefined}
Uncaught (in promise) reject

The last Uncaught (in promise) reject looks to be odd here, because the promise was properly handled.

Here is another example, where the promise rejection was not handled:

Promise.reject('reject')
  .finally(() => console.warn('finally'));

and the output is:

finally
Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: "reject"}
Uncaught (in promise) reject
Uncaught (in promise) reject

The promise rejection was not handled at all and we got two unhandledrejection instead of one.

Each new finally in promise chain will produce one extra unhandledrejection event. This will result in four events triggered:

Promise.reject('reject')
  .finally(() => console.warn('finally'))
  .finally(() => console.warn('finally'))
  .finally(() => console.warn('finally'));

Does this correct behaviour? If yes, then how should I handle those extra rejections?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

An in-range update of eslint is breaking the build 🚨

The devDependency eslint was updated from 6.7.2 to 6.8.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details

Release Notes for v6.8.0
  • c5c7086 Fix: ignore aligning single line in key-spacing (fixes #11414) (#12652) (YeonJuan)
  • 9986d9e Chore: add object option test cases in yield-star-spacing (#12679) (YeonJuan)
  • 1713d07 New: Add no-error-on-unmatched-pattern flag (fixes #10587) (#12377) (ncraley)
  • 5c25a26 Update: autofix bug in lines-between-class-members (fixes #12391) (#12632) (YeonJuan)
  • 4b3cc5c Chore: enable prefer-regex-literals in eslint codebase (#12268) (薛定谔的猫)
  • 05faebb Update: improve suggestion testing experience (#12602) (Brad Zacher)
  • 05f7dd5 Update: Add suggestions for no-unsafe-negation (fixes #12591) (#12609) (Milos Djermanovic)
  • d3e43f1 Docs: Update no-multi-assign explanation (#12615) (Yuping Zuo)
  • 272e4db Fix: no-multiple-empty-lines: Adjust reported loc (#12594) (Tobias Bieniek)
  • a258039 Fix: no-restricted-imports schema allows multiple paths/patterns objects (#12639) (Milos Djermanovic)
  • 51f9620 Fix: improve report location for array-bracket-spacing (#12653) (Milos Djermanovic)
  • 45364af Fix: prefer-numeric-literals doesn't check types of literal arguments (#12655) (Milos Djermanovic)
  • e3c570e Docs: Add example for expression option (#12694) (Arnaud Barré)
  • 6b774ef Docs: Add spacing in comments for no-console rule (#12696) (Nikki Nikkhoui)
  • 7171fca Chore: refactor regex in config comment parser (#12662) (Milos Djermanovic)
  • 1600648 Update: Allow $schema in config (#12612) (Yordis Prieto)
  • acc0e47 Update: support .eslintrc.cjs (refs eslint/rfcs#43) (#12321) (Evan Plaice)
  • 49c1658 Chore: remove bundling of ESLint during release (#12676) (Kai Cataldo)
  • 257f3d6 Chore: complete to move to GitHub Actions (#12625) (Toru Nagashima)
  • ab912f0 Docs: 1tbs with allowSingleLine edge cases (refs #12284) (#12314) (Ari Kardasis)
  • dd1c30e Sponsors: Sync README with website (ESLint Jenkins)
  • a230f84 Update: include node version in cache (#12582) (Eric Wang)
  • 8b65f17 Chore: remove references to parser demo (#12644) (Kai Cataldo)
  • e9cef99 Docs: wrap {{}} in raw liquid tags to prevent interpolation (#12643) (Kai Cataldo)
  • e707453 Docs: Fix configuration example in no-restricted-imports (fixes #11717) (#12638) (Milos Djermanovic)
  • 19194ce Chore: Add tests to cover default object options in comma-dangle (#12627) (YeonJuan)
  • 6e36d12 Update: do not recommend require-atomic-updates (refs #11899) (#12599) (Kai Cataldo)
Commits

The new version differs by 29 commits.

  • 9738f8c 6.8.0
  • ba59cbf Build: changelog update for 6.8.0
  • c5c7086 Fix: ignore aligning single line in key-spacing (fixes #11414) (#12652)
  • 9986d9e Chore: add object option test cases in yield-star-spacing (#12679)
  • 1713d07 New: Add no-error-on-unmatched-pattern flag (fixes #10587) (#12377)
  • 5c25a26 Update: autofix bug in lines-between-class-members (fixes #12391) (#12632)
  • 4b3cc5c Chore: enable prefer-regex-literals in eslint codebase (#12268)
  • 05faebb Update: improve suggestion testing experience (#12602)
  • 05f7dd5 Update: Add suggestions for no-unsafe-negation (fixes #12591) (#12609)
  • d3e43f1 Docs: Update no-multi-assign explanation (#12615)
  • 272e4db Fix: no-multiple-empty-lines: Adjust reported loc (#12594)
  • a258039 Fix: no-restricted-imports schema allows multiple paths/patterns objects (#12639)
  • 51f9620 Fix: improve report location for array-bracket-spacing (#12653)
  • 45364af Fix: prefer-numeric-literals doesn't check types of literal arguments (#12655)
  • e3c570e Docs: Add example for expression option (#12694)

There are 29 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

`Promise.prototype.finally` requires a global `Promise` be available

Running the shim in a Chrome Version 52.0.2743.116 (64-bit) raises an error complaining about the lack of a global Promise function.

requirePromise.js:5 Uncaught TypeError: `Promise.prototype.finally` requires a global `Promise` be available.

Given that there is definitely such function there, shouldn't the code requirePromise.js look further for it?
Wouldn't it be appropriate to change the verification to something like the following?

if (typeof (Promise || global.Promise || window.Promise) !== 'function') {
    throw ...
}

TODO: fix tests on node v6.0-v6.4

One of the subclassing tests fails on these node versions. Either the polyfill code should detect this, or if not possible synchronously, skip the failing tests.

The current proposal returns a `Promise`, not the `Symbol.species` constructor.

I'm specifically looking at these two abstract operations, which basically does this:

var PromiseResolve = Promise.resolve.bind(Promise)
var PromiseThen = Function.call.bind(Promise.prototype.then)

function CreateThenFinally(onFinally) {
    if (typeof onFinally !== "function") return onFinally
    return function (value) {
        return PromiseThen(PromiseResolve(onFinally()), function () { return value })
    }
}

function CreateCatchFinally(onFinally) {
    if (typeof onFinally !== "function") return onFinally
    return function (value) {
        return PromiseThen(PromiseResolve(onFinally()), function () { throw value })
    }
}

An in-range update of es-abstract is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye 👋 and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The dependency es-abstract was updated from 1.17.4 to 1.17.5.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

es-abstract is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details

Commits

The new version differs by 5 commits.

  • 3641bbb v1.17.5
  • bdd77b5 [Fix] CreateDataProperty: update an existing property
  • 920a682 [Dev Deps] update make-arrow-function, tape
  • b9069ac [Fix] run missing spackle from cd7504701879ddea0f5981e99cbcf93bfea9171d
  • 9f1690f [Dev Deps] update @ljharb/eslint-config

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

this._c is undefined

This might be related to #4 as it only happens with Firefox, but I couldn't figure out the root cause and I don't have a minimal example.

Setup:

promise = ...fetch(...)
promiseFinally(promise, () => ...)

Now at some point we hit

this._c is undefined

in this line: https://github.com/zloirock/core-js/blob/0bb657cfc7834d03fd68c48a1cba70f2ccab20c0/modules/es6.promise.js#L212

this is window when the error happens, which is obviously wrong. So something seems to be wrongly bound there.

I'm not even sure this is an issue with this library, but it goes away when I switch to es6-promise.

Crashes on iOS 10.3

I don't have many details because I don't have iDevices but a teammate had to remove the polyfill because it's crashing on iOS 10.3

image

on iOS 10.2 this doesn't happen and the polyfill works without any issues

Add browser file

It be nice if the npm package ships with a single file that needs to be included to polyfill finally globally in the browser.

Fails on IE11

We get
SCRIPT5007: Unable to get property 'configurable' of undefined or null reference
on line
if (Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(promiseFinally, 'name').configurable)

We are using Profile polyfill from https://github.com/zloirock/core-js

An in-range update of es-abstract is breaking the build 🚨

The dependency es-abstract was updated from 1.17.0-next.1 to 1.17.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

es-abstract is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details

Commits

The new version differs by 12 commits.

  • 91c2c22 v1.17.0
  • 96719b9 [Dev Deps] update @ljharb/eslint-config
  • c52fa59 [Fix] GetIntrinsic: IE 8 has a broken Object.getOwnPropertyDescriptor
  • fb308ec [Deps] update is-callable, string.prototype.trimleft, string.prototype.trimright
  • b84552d [Dev Deps] update tape
  • 9be0385 [Refactor] GetIntrinsic: further simplification
  • 0c7f99a [Tests] add .eslintignore
  • e2df4de [Dev Deps] update object-is
  • 158ed34 [Deps] update is-regex
  • 3567ae9 [Refactor] GetIntrinsic: remove the internal property salts, since % already handles that
  • 84c50fb [Dev Deps] update object.fromentries
  • f0b1083 [meta] remove unused Makefile and associated utils

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Loading the polyfill on Chrome 67 will raise a warning

When using this code in my project:

import promiseFinally from 'promise.prototype.finally';
promiseFinally.shim();

I will see this warning in Chrome 67.0.3396.87 console:
index.js:51 [Deprecation] Application Cache is deprecated in non-secure contexts, and will be restricted to secure contexts in M69, around September 2018. Please consider migrating your application to HTTPS, and eventually shifting over to Service Workers. See https://goo.gl/rStTGz for more details.

Not working in firefox

Hello, I have this error .fetch(...).then(...).finally is not a function, in firefox (latest version) only. If I remove all .finally(() => { }); functions for the app it works, also if I run it with webpack dev server works, but in production or with webpack dev server with the -p flag it doesn't work anymore.

I'm using 2.0.1 version, but I tried the latest 3.0.1 too and same, didn't do nothing. Any ideas?

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.