Git Product home page Git Product logo

lie's Introduction

lie

Promises/A+ logo Build status

lie is a small, performant promise library implementing the Promises/A+ spec (Version 1.1).

Originally a fork of Ruben Verborgh's promiscuous, with version 2.6 it became a fork of ayepromise by Chris Burgmer.

npm install lie
var Promise = require('lie');
// or use the pollyfill
require('lie/polyfill');

Usage

Either use it with browserify (recommended) or grab one of the files from the dist folder:

  • lie.js/lie.min.js exposes 'Promise' either as a UMD module or from the global scope, depending on if a CJS or AMD loader is available.
  • lie.polyfill.js/lie.polyfill.min.js adds 'Promise' to the global scope only if it's not already defined (not a UMD).

API

Implements the standard ES6 api:

new Promise(function(resolve, reject){
    doSomething(function(err, result) {
        if (err) {
            reject(err);
        } else {
            resolve(result);
        }
    });
}).then(function (value) {
    //on success
}, function (reason) {
    //on error
}).catch(function (reason) {
    //shortcut for error handling
});

Promise.all([
    //array of promises or values
]).then(function ([/* array of results */]));

Promise.race([
    //array of promises or values
]);
// either resolves or rejects depending on the first value to do so

Unhandled Rejections

In Node.js, lie emits an unhandledRejection event when a rejected promise isn't caught, in line with how io.js does it. This allows it to act as a promise shim in both Node.js and the browser.

lie's People

Contributors

andrewiggins avatar calvinmetcalf avatar haroenv avatar nolanlawson avatar nswbmw avatar rubenverborgh avatar valve 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lie's Issues

Adding a .finally() method would be nice (src included)

Although not included in ES6. The finally() method is very valuable.

Here's one implementation:

Promise.prototype.finally = function(callback) {
  var p = this.constructor;
  // We don’t invoke the callback in here,
  // because we want then() to handle its exceptions
  return this.then(
    // Callback fulfills: pass on predecessor settlement
    // Callback rejects: pass on rejection (=omit 2nd arg.)
    function(value) {
      p.resolve(callback()).then(function() { return value; });
    },
    function(reason) {
      p.resolve(callback()).then(function() { throw reason; });
    }
  );
}

Idiomatic way to use this inside a promise function

Hi, Great library!

What are the options of using this inside a promise function?

return new Promise(function(resolve, reject){
  // I want to access this here, but it's a global object, not current object
});

I can use good old that:

var that = this;
return new Promise(function(resolve, reject){
  that.callMethod();
});

I also could use bind.

return new Promise(function(resolve, reject){
  this.callMethod();
}.bind(this));

Which is my preferred way, but I'm afraid it could break lie in unexpected ways.

Please let me know of a preferred way of using this.

Thanks

It is different from es6-Promise,when resolve a promise.below is the code and result

below is the code and result

code

    function fn1() {
        console.log("async1 start", 1);
        return new Promise((r) => {
          r(fn2());                                          // resolve a promise
        }).then(() => console.log("async1 end", 4));
      }

      function fn2() {
        console.log("async2", 2);
        return new Promise((r) => {
          r(123);
        });
      }

      setTimeout(() => {
        console.log("timeout", 8);
      }, 0);

      fn1();

      new Promise((r) => {
        console.log("promise", 3);
        r();
      })
        .then((d) => {
          console.log("promise2", 5);
        })
        .then((d) => {
          console.log("promise3", 6);
        })
        .then((d) => {
          console.log("promise4", 7);
        });

es6-Promise result
image

lie result
image

Exception Goblins

I really like the library, but there's one major flaw/annoyance that constantly happens when trying to use it. And that is how it silently gobbles up errors, and lack of any ability to tell it to (at least temporarily) not do so.

I understand this is probably due to the minimal nature or standard compliance but it would be really nice to have some global switch like debug we can turn on to force lie to spit out the errors. Doesn't need to be any fancy reporting either, something basic like console.log(err.stack || err) would do just fine; since in most cases it's just very simple mistakes that are just made complicated only by the fact they are not surfaced by lie.

This would be good not just for cases where the system unexpectedly fails but also for cases where the system continues to work even though there's been some serious failures; which are the worst.

Some of the annoying goblin cases:

var Promise = require('lie');

errno = 0;

// throws error before resolve/reject are called
++errno;
var p = new Promise(function (resolve, reject) {
    throw new Error('Error #' + errno);
});

// resolves but throws error in resolver
++errno;
var p = new Promise(function (resolve, reject) {
    resolve(true);
}).then(function (d) {
    throw new Error('Error #' + errno);
});

// rejects with an Error object
// this may be personal bias but if it's specifically an Error object it
// never really makes sense to silently ignore it (other objects its fine)
++errno;
var p = new Promise(function (resolve, reject) {
    reject(new Error('Error #' + errno));
}).then(function (d) {
    // no reject handler
});

// does not resolve nor reject; there should be a debugTimeout
++errno;
var p = new Promise(function (resolve, reject) {
    // empty
}).then(function (d) {
    // do nothing
});

console.log(errno + ' errors should have happened');

A lot of the time the silent gobbling up just results in adding pointless try / catch for the purpose of just surfacing the error, only to remove them immediately after since there's no reason at all to do anything inside them other then overcome this annoyance in lie.

Webpack throws Warning

I know dist/lie.js is not pre-built, but it still throw this warning due to the way its written...

WARNING in ./~/lie/dist/lie.js
Critical dependencies:
1:438-445 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/lie/dist/lie.js 1:438-445

For easier tracking of the error here's the warning as it appears when I require('lie/lib'),

WARNING in ./~/lie/~/immediate/dist/immediate.js
Critical dependencies:
1:440-447 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/lie/~/immediate/dist/immediate.js 1:440-447

Incidentally I would prefer that the raw source (and by this I also mean require'ing the raw source on dependencies too) was actually the default when doing require('lie') since I believe the concatenated version may have issues with deduping but its not much of a issue otherwise, other then being hard to spot, since I personally alias all 3rd party libraries.

Expecting a function in instanceof check, but got #<Object>

Happens at

exports.resolve = resolve;
function resolve(value) {
  if (value instanceof this) {
    return value;
  }
  return handlers.resolve(new this(INTERNAL), value);
}

I'm using Opera 36 (the newest, Chromium-based), it seems to expect this to be a function, but it is

Object {
  all: all(iterable)
  default: Promise(resolver)
  race: race(iterable)
  reject: reject(reason)
  resolve: resolve(value)
  __proto__: Object
}

Inappropriate unhandled rejection error?

I wrote a silly library that lets us enqueue functions and run them serially. That is, each function won't be invoked until the function before it has completed. Each of the functions is itself asynchronous so we use promises both to let those enqueuing the functions track them as well as to manage executing them in order.

The problem I'm running into is that I'm getting an unhandled rejection error on a promise whose rejection is handled. The error is caused by the rejection of a promise that is successfully caught in a catch handler.

The rejected promise is defined here and the successfully run catch handler is defined here. The test makes sure that the catch handler is properly called.

The code that this is executing is defined here and as you can see it uses two nested promises. The outer promise is returned to the enqueued caller and it is only this promise which will be rejected. Inside of it is a second promise that we use to manage the queue. Only it's resolve function (called globalResolve) will be called regardless of the outcome of the outer promise.

I know this format is a bit unorthodox but as I think the test shows we are handling the rejection so why are we still getting the unhandled rejection error?

Thanks! And I apologize in advance if this is something I'm screwing up on my side.

immediate still brings in browserify transforms

So unfortunately 3.1.0 didn't reduce node_modules or install times by much:

lie

However, upgrading to latest immediate gives us a 2.3kB build size instead of 1.7kB.

A few possible solutions:

  1. Fork the old version of immediate into a pretransformed version (e.g. immediate-lie), use that as the dep
  2. Move the old version of immediate into this repo

What do you think?

performance takes a nose dive resolving 12 promises

but not 11, wtf?

doing 11

results for 10000 parallel executions, 1 ms per I/O op

file                           time(ms)  memory(MB)
callbacks-baseline.js               534       25.48
promises-bluebird.js                666       48.99
promises-cujojs-when.js            1675      117.34
promises-calvinmetcalf-lie.js      2198      188.46
promises-then-promise.js           5176      263.32
promises-tildeio-rsvp.js           8814      313.01

Platform info:
Linux 3.13.0-24-generic x64
Node.JS 0.10.26
V8 3.14.5.9
Intel(R) Core(TM) i3 CPU       M 380  @ 2.53GHz × 4

everything the same but 12 instead of 11

results for 10000 parallel executions, 1 ms per I/O op

file                           time(ms)  memory(MB)
callbacks-baseline.js               568       25.52
promises-bluebird.js                678       93.76
promises-cujojs-when.js            1747      148.11
promises-then-promise.js           4873      290.60
promises-tildeio-rsvp.js           9983      372.64
promises-calvinmetcalf-lie.js    103301      196.20

Platform info:
Linux 3.13.0-24-generic x64
Node.JS 0.10.26
V8 3.14.5.9
Intel(R) Core(TM) i3 CPU       M 380  @ 2.53GHz × 4

likely not an issue with Promise.all as replacing our current one with the one from then/promise has the same result

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.