Skip to content

Instantly share code, notes, and snippets.

@developit
Last active January 16, 2023 17:25
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save developit/d970bac18430943e4b3392b029a2a96c to your computer and use it in GitHub Desktop.
Save developit/d970bac18430943e4b3392b029a2a96c to your computer and use it in GitHub Desktop.

finally-polyfill

A tiny ~150-byte polyfill for Promise.prototype.finally.

Useful for browsers that support Promise but not the .finally() method.

Usage

npm install finally-polyfill

It's a polyfill, so you can import, require() or drop it in a script tag - all the same.

import 'finally-polyfill';
Promise.reject('oops').finally(() => { /* ... */ })
<script src="/path/to/finally-polyfill.min.js"></script>

License

MIT

if (!Promise.prototype.finally) {
Promise.prototype.finally = function(callback) {
if (typeof callback !== 'function') {
return this.then(callback, callback);
}
const P = this.constructor || Promise;
return this.then(
value => P.resolve(callback()).then(() => value),
err => P.resolve(callback()).then(() => { throw err; })
);
};
}
Promise.prototype.finally||(Promise.prototype.finally=function(t){if("function"!=typeof t)return this.then(t,t);const e=this.constructor||Promise;return this.then(o=>e.resolve(t()).then(()=>o),o=>e.resolve(t()).then(()=>{throw o}))})
{
"version": "0.2.0",
"name": "finally-polyfill",
"main": "finally-polyfill.min.js",
"author": "Jason Miller <jason@developit.ca>",
"repo": "gist:d970bac1843",
"homepage": "https://gist.github.com/developit/d970bac18430943e4b3392b029a2a96c",
"scripts": { "prepack": "mv *finally-polyfill.md README.md", "postpack": "mv README.md *finally-polyfill.md" },
"license": "MIT"
}
@guoyunhe
Copy link

If you use create-react-app or similar tool (with browserlists config ie: 11), babel will do this transform for you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment