A polyfill for ES6-style Promises

Overview

ES6-Promise (subset of rsvp.js) Build Status

This is a polyfill of the ES6 Promise. The implementation is a subset of rsvp.js extracted by @jakearchibald, if you're wanting extra features and more debugging options, check out the full library.

For API details and how to use promises, see the JavaScript Promises HTML5Rocks article.

Downloads

CDN

To use via a CDN include this in your html:

<!-- Automatically provides/replaces `Promise` if missing or broken. -->
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script> 

<!-- Minified version of `es6-promise-auto` below. -->
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script> 

Node.js

To install:

yarn add es6-promise

or

npm install es6-promise

To use:

var Promise = require('es6-promise').Promise;

Usage in IE<9

catch and finally are reserved keywords in IE<9, meaning promise.catch(func) or promise.finally(func) throw a syntax error. To work around this, you can use a string to access the property as shown in the following example.

However most minifiers will automatically fix this for you, making the resulting code safe for old browsers and production:

promise['catch'](function(err) {
  // ...
});
promise['finally'](function() {
  // ...
});

Auto-polyfill

To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet:

require('es6-promise').polyfill();

Alternatively

require('es6-promise/auto');

Notice that we don't assign the result of polyfill() to any variable. The polyfill() method will patch the global environment (in this case to the Promise name) when called.

Building & Testing

You will need to have PhantomJS installed globally in order to run the tests.

npm install -g phantomjs

  • npm run build to build
  • npm test to run tests
  • npm start to run a build watcher, and webserver to test
  • npm run test:server for a testem test runner and watching builder
Comments
  • allow reverting to native Promise

    allow reverting to native Promise

    I was quite surprised that on Chrome I saw that window.Promise was changed from the native one when I use this library as I intentionally didnt call the polyfill method. Then i saw the code:

    Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast)
    

    and realized the issue as in Chrome this test fails (as reported multiple times #139 #136 #132 ...)

    Normally I wouldnt care this much but Im working on a project in which my code is inserted into other websites and I dont wish to change anything on the global level and unfortunately using this library violates this rule.

    Its my opinion that the explanation that the native imp may have issues/bugs is irrelevant for cjs/amd environments. The library shouldnt touch the global object unless explicitly requested., But if you still wish to leave it as it is, please give us the ability to revert back to the original/native Promise. a long the lines of noConflict.

    Thanks! Yoav

    opened by yoavniran 47
  • TypeError: Cannot read property 'length' of undefined

    TypeError: Cannot read property 'length' of undefined

    Node version: 4.3.1 OS: Mac EL Captain (10.11.3)

    Error is thrown while using grunt-nodemon which has a dependency with "es6-promise" package. Error details are given below,

    TypeError: Cannot read property 'length' of undefined at lib$es6$promise$$internal$$fulfill (/Users/kt/node_modules/grunt-nodemon/node_modules/nodemon/node_modules/es6-promise/dist/es6-promise.js:303:31) at lib$es6$promise$$internal$$resolve (/Users/kt/node_modules/grunt-nodemon/node_modules/nodemon/node_modules/es6-promise/dist/es6-promise.js:285:9) at lib$es6$promise$$internal$$invokeCallback (/Users/kt/node_modules/grunt-nodemon/node_modules/nodemon/node_modules/es6-promise/dist/es6-promise.js:396:9) at /Users/kt/node_modules/grunt-nodemon/node_modules/nodemon/node_modules/es6-promise/dist/es6-promise.js:166:11 at lib$es6$promise$asap$$flush (/Users/kt/node_modules/grunt-nodemon/node_modules/nodemon/node_modules/es6-promise/dist/es6-promise.js:119:9) at doNTCallback0 (node.js:419:9) at process._tickDomainCallback (node.js:389:13) at Function.Module.runMain (module.js:469:11) at startup (node.js:136:18) at node.js:963:3

    opened by kamalt 24
  • Automatic polyfill

    Automatic polyfill

    It seems this polyfill requires you to call ES6Promise.polyfill() before it will work. Wouldn't it be better if it created a global Promise if it cannot find the global Promise?

    opened by mariusGundersen 21
  • Doesn't work in IE11

    Doesn't work in IE11

    It looks like MutationObserver isn't firing in IE11. Paste this into the console:

    ES6Promise.Promise.resolve("hello").then(function(v){console.log(v);});
    

    This won't fire. If I then paste this:

    setTimeout(function(){},1);
    

    Then both the setTimeout event AND the .then() callback function get called. This must be some kind of IE bug? I couldn't find anyone reporting it though so I must be mistaken?

    opened by altano 19
  • vertx module not found

    vertx module not found

    Getting this when using es6-promise 2.1.0 with webpack-dev-server: ./~/es6-promise/dist/es6-promise.js Module not found: Error: Cannot resolve module 'vertx' in C:\web\node_modules\es6-promise\dist

    opened by terebentina 19
  • Can't use polyfill since v2.0

    Can't use polyfill since v2.0

    Requiring promise.js doesn't polyfill Promise since version 2.0 as it seems it requires a JavaScript loader now.

    Version 1.0 of the polyfill could be used as normal JavaScript:

    <script src=promise.js></script>
    <script>new Promise</script>
    

    This was broken in v2.0.

    opened by mislav 18
  • Browser support

    Browser support

    This polyfill looks super cool. However I couldn't find the browser support that this has. Any idea of which browsers support this implementation? It'll be really cool to have this information clearly defined in the README.

    Thanks!

    opened by rafayepes 17
  • [Question] Scheduling issue with node ?

    [Question] Scheduling issue with node ?

    Based on a comment from @jakearchibald.

    Jack I had decided to look at the implementation for setImmediate() and took an other look at your comment:

    setImmediate(_ => console.log(1));
    Promise.resolve().then(_ => console.log(2));
    setImmediate(_ => console.log(3));
    

    The above will currently log 1,2,3, is the aim of this PR to make it 1,3,2 if zone.js is present? If so, I'm a little worried about it as it breaks es6.

    It seems wrong when I looked at it again this morning:

    • setImmediate() should enqueue on the macrotask queue,
    • .then() should use the microtask queue,
    • the expected result is then "2, 1, 3" - which it is when you executed this code with node 0.12

    Now looking at the code again, asap() indeed uses setImmediate() on node 0.10. So when run with node 0.10, the result of

    setImmediate(_ => console.log(1));
    ES6Promise.Promise.resolve().then(_ => console.log(2));
    setImmediate(_ => console.log(3));
    

    will be "1, 2, 3" which is not expected.

    I'm unsure if there is a better way to enqueue a microtask with Node 0.10 (as nextTick could not be used according to the comment).

    If I'm right, this looks like an issue of ES6Promise ? if so it should probably be documented

    edit: some background info on process.nextTick() - TL;DR: pre-0.9, it enqueues a macrotask.

    opened by vicb 16
  • 2.1.0 requires vertx, but it is not a dependency in package.json

    2.1.0 requires vertx, but it is not a dependency in package.json

    I get an error like this when using axios, and it seems to come from this library.

    "./~/axios/~/es6-promise/dist/es6-promise.js
    Module not found: Error: Cannot resolve module 'vertx' in /home/user/workspaces/company/project/node_modules/axios/node_modules/es6-promise/dist
    resolve module vertx in /home/user/workspaces/company/project/node_modules/axios/node_modules/es6-promise/dist
      looking for modules in /home/user/workspaces/company/project/node_modules/axios/node_modules
        /home/user/workspaces/company/project/node_modules/axios/node_modules/vertx doesn't exist (module as directory)
        resolve 'file' vertx in /home/user/workspaces/company/project/node_modules/axios/node_modules
          resolve file
            /home/user/workspaces/company/project/node_modules/axios/node_modules/vertx doesn't exist
            /home/user/workspaces/company/project/node_modules/axios/node_modules/vertx.js doesn't exist
            /home/user/workspaces/company/project/node_modules/axios/node_modules/vertx.json doesn't exist
      looking for modules in /home/user/workspaces/company/project/node_modules
        /home/user/workspaces/company/project/node_modules/vertx doesn't exist (module as directory)
        resolve 'file' vertx in /home/user/workspaces/company/project/node_modules
          resolve file
            /home/user/workspaces/company/project/node_modules/vertx doesn't exist
            /home/user/workspaces/company/project/node_modules/vertx.js doesn't exist
            /home/user/workspaces/company/project/node_modules/vertx.json doesn't exist
      looking for modules in /home/user/node_modules
        /home/user/node_modules/vertx doesn't exist (module as directory)
        resolve 'file' vertx in /home/user/node_modules
          resolve file
            /home/user/node_modules/vertx doesn't exist
            /home/user/node_modules/vertx.js doesn't exist
            /home/user/node_modules/vertx.json doesn't exist
    [/home/user/workspaces/company/project/node_modules/axios/node_modules/vertx]
    [/home/user/workspaces/company/project/node_modules/axios/node_modules/vertx]
    [/home/user/workspaces/company/project/node_modules/axios/node_modules/vertx.js]
    [/home/user/workspaces/company/project/node_modules/axios/node_modules/vertx.json]
    [/home/user/workspaces/company/project/node_modules/vertx]
    [/home/user/workspaces/company/project/node_modules/vertx]
    [/home/user/workspaces/company/project/node_modules/vertx.js]
    [/home/user/workspaces/company/project/node_modules/vertx.json]
    [/home/user/node_modules/vertx]
    [/home/user/node_modules/vertx]
    [/home/user/node_modules/vertx.js]
    [/home/user/node_modules/vertx.json]
     @ ./~/axios/~/es6-promise/dist/es6-promise.js 125:20-30"
    
    opened by 0xR 16
  • Use native polyfill on Chrome and Node.js v0.12

    Use native polyfill on Chrome and Node.js v0.12

    On v8 based Javascript engines, the check for using the native Polyfill implementations fails because the check

    Object.prototype.toString.call(P.resolve())
    

    return [object Object] instead of the expected [object Promise], that only happens to be on Firefox. I think this check should be less strict or use other condition so v8 native Promises can be used.

    opened by piranna 15
  • Errors not thrown

    Errors not thrown

    Chrome 41 throws uncatched errors using native window.Promise:

    new window.Promise(function(res, rej) {
      throw new Error('window.Promise');
    });
    

    The only way i can achieve this behavior using es6-promise is by re-throwing in a setTimeout in catch:

    var Promise = require('es6-promise');
    
    new Promise(function(res, rej) {
      throw new Error('es6-promise');
    }).catch(function(err) {
      setTimeout(function() {
        throw err;
      }, 0);
    });
    

    This is not developer-friendly at all. While i've read #70, #71 and especially #40 i don't get how this is specced behavior. Can't find anything in the current ES6 draft on this.

    Maybe someone can shed a little light.

    opened by codepunkt 15
  • incompatible with ie11 + babel + webpack

    incompatible with ie11 + babel + webpack

    see: https://github.com/embroider-build/embroider/issues/677#issuecomment-813118275 and https://github.com/emberjs/ember-test-waiters/pull/308 for more details

    bug 
    opened by stefanpenner 0
  • Switch build to Babel 7?

    Switch build to Babel 7?

    There is a babel-upgrade tool to automate upgrade and full changes in babel 7 here https://babeljs.io/blog/2018/08/27/7.0.0

    We'd like to remove babel 6 from next version of debian and switched to using babel 7 for building es6-promise but it'd be nice to stay close to the versions you use.

    enhancement 
    opened by pravi 1
  • Is it required to include both scripts in html page?

    Is it required to include both scripts in html page?

    <!-- Automatically provides/replaces `Promise` if missing or broken. -->
    <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script> 
    
    <!-- Minified version of `es6-promise-auto` below. -->
    <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script> 
    
    • What is different between es6-promise.js and es6-promise.auto.js?
    • Is it required to include both scripts in html page?
    • What happens if just include either of es6-promise.js or es6-promise.auto.js?
    opened by dehghani-mehdi 2
  • Missing polyfill for Promise.allSettled

    Missing polyfill for Promise.allSettled

    Now that Promise.allSettled reached stage 4 of the specification process, would it make sense to add a polyfill for it to this project?

    Or would you rather recommend to add a separate shim for it, something like es-shims/Promise.allSettled ? IMO that's less convenient, but creating yet another implementation also sounds wrong.

    needs submitter response 
    opened by codeworrior 7
  • .d.ts incompatible with TypeScript lib definitions

    .d.ts incompatible with TypeScript lib definitions

    import { Promise as Promise6 } from "es6-promise";
    
    export const error: Promise6<void> = Promise.resolve();
    export const error2: Promise<void> = Promise6.resolve();
    

    Sandbox With "lib": ["es5", "es2015.promise"], error fails to compile with the message:

    Property 'finally' is missing in type 'Promise<void>' but required in type 'Promise<void>'.
    

    Sandbox With "lib": ["es5", "es2015.promise", "es2018.promise"], error fails to compile with the message:

    Type 'Promise<void>' is not assignable to type 'import("/sandbox/node_modules/es6-promise/es6-promise").Promise<void>'.
      Types of property 'catch' are incompatible.
        Type '<TResult = never>(onrejected?: (reason: any) => TResult | PromiseLike<TResult>) => Promise<void | TResult>' is not assignable to type '<U>(onRejected?: (error: any) => U | Thenable<U>) => Promise<U>'.
          Type 'Promise<void | U>' is not assignable to type 'Promise<U>'.
            Types of property 'then' are incompatible.
              Type '<TResult1 = void | U, TResult2 = never>(onfulfilled?: (value: void | U) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<TResult1 | TResult2>' is not assignable to type '{ <U>(onFulfilled?: (value: U) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Promise<U>; <U>(onFulfilled?: (value: U) => U | Thenable<U>, onRejected?: (error: any) => void): Promise<...>; }'.
                Types of parameters 'onfulfilled' and 'onFulfilled' are incompatible.
                  Types of parameters 'value' and 'value' are incompatible.
                    Type 'void | U' is not assignable to type 'U'.
                      Type 'void' is not assignable to type 'U'.
    

    Sandbox Using es6 (or newer) in place of es5 above gives the same message for error, but adds another failure for error2 with the message:

    Property '[Symbol.toStringTag]' is missing in type 'Promise<void>' but required in type 'Promise<void>'
    

    The error2 message was brought up in #300, which was closed without a fix.

    It's really frustrating working with libraries that use es6-promise and export the type in their signatures, because you need to wrap the promises or cast away all type safety.

    Are there any TypeScript lib configurations that are compatible with this library's typings, or are there any plans to update the definitions to be compatible?

    opened by michens 0
Owner
Stefan Penner
Stefan Penner
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Base62-token.js - Generate & Verify GitHub-style & npm-style Base62 Tokens

base62-token.js Generate & Verify GitHub-style & npm-style Secure Base62 Tokens Works in Vanilla JS (Browsers), Node.js, and Webpack. Online Demo See

Root 4 Jun 11, 2022
Use plain functions as modifiers. Polyfill for RFC: 757 | Default Modifier Manager

Use plain functions as modifiers. Polyfill for RFC: 757 | Default Modifier Manager

null 7 Jan 14, 2022
Polyfill to remove click delays on browsers with touch UIs

FastClick FastClick is a simple, easy-to-use library for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile

FT Labs 18.8k Jan 2, 2023
Javascript client for Sanity. Works in node.js and modern browsers (older browsers needs a Promise polyfill).

@sanity/client Javascript client for Sanity. Works in node.js and modern browsers (older browsers needs a Promise polyfill). Requirements Sanity Clien

Sanity 23 Nov 29, 2022
PouchDB for Deno, leveraging polyfill for IndexedDB based on SQLite.

PouchDB for Deno PouchDB for Deno, leveraging polyfill for IndexedDB based on SQLite. Usage import PouchDB from 'https://deno.land/x/[email protected]

Aaron Huggins 19 Aug 2, 2022
Window.fetch polyfill

window.fetch polyfill This project adheres to the [Open Code of Conduct][code-of-conduct]. By participating, you are expected to uphold this code. [co

null 38 Sep 11, 2020
Polyfill `error.cause`

Polyfill error.cause. error.cause is a recent JavaScript feature to wrap errors. try { doSomething() } catch (cause) { throw new Error('message',

ehmicky 4 Dec 15, 2022
Fast and lightweight dependency-free vanilla JavaScript polyfill for native lazy loading / the awesome loading='lazy'-attribute.

loading="lazy" attribute polyfill Fast and lightweight vanilla JavaScript polyfill for native lazy loading, meaning the behaviour to load elements rig

Maximilian Franzke 571 Dec 30, 2022
Awesome book with ES6, this project is build using HTML,CSS, JavaScript ES6 the project allows you to add books and save them with the author , for another time checks

Project Name Awsome books Description the project. adding books daynamiclly Built With Major languages Frameworks Technologies used Live Demo (if avai

Alzubair Alqaraghuli 5 Jul 25, 2022
Awesome Books project with ES6 is an application that was built using Vanilla JavaScript with ES6 features like using arrow functions. This application allows you to keep records of your favorite books.

Javascript Project Awesome Books with ES6 Using Javascript to create a simple Awesome Books project. Populating the books list and then removing one b

Ghazanfar Ali 8 Sep 28, 2022
In this project, I restructure my previous Awesome books app code. The goal is to practice ES6 syntax and also make the code more organized by using ES6 modules.

Awesome Books In this project, I will restructure my previous Awesome books app code. The goal is to make it more organized by using modules. I will a

Sidney Kaguli 9 Aug 23, 2022
Run async code one after another by scheduling promises.

promise-scheduler Run async code in a synchronous order by scheduling promises, with the possibility to cancel pending or active tasks. Optimized for

Matthias 2 Dec 17, 2021
Resolve parallel promises in key-value pairs whilst maintaining type information

async-kv Resolves promises in key-value pairs maintaining type information. Prerequisites NodeJS 12 or later Installation npm i async-kv yarn add asyn

Tony Tamplin 4 Feb 17, 2022
🐶 Learn JS Promises, with your friend 👑 Princess!

?? Learn JS Promises, with your friend ?? Princess!

Baylee Schmeisser 10 Jun 9, 2022
Converts an iterable, iterable of Promises, or async iterable into a Promise of an Array.

iterate-all A utility function that converts any of these: Iterable<T> Iterable<Promise<T>> AsyncIterable<T> AsyncIterable<Promise<T>> Into this: Prom

Lily Scott 8 Jun 7, 2022
Ajax library with XHR2, promises and request limit

qwest 4.5.0 ⚠ I finally decided to archive this repository. ⚠ At first, I developed Qwest because at the time other libraries were lacking of a proper

Aurélien Delogu 718 Sep 14, 2022
A request library that returns promises, inspired by request

then-request A request library that returns promises and supports both browsers and node.js Installation npm install then-request Usage request(metho

then (Promises/A+ implementations) 241 Nov 29, 2022