then / promise Goto Github PK
View Code? Open in Web Editor NEWBare bones Promises/A+ implementation
Home Page: https://www.promisejs.org
License: MIT License
Bare bones Promises/A+ implementation
Home Page: https://www.promisejs.org
License: MIT License
var O = function() {
this.test = 'hi';
};
O.prototype.aFunction = function() {
this.test = 'bye';
};
var o = new O();
Promise.denodeify(o.aFunction)();
The promise fails with this
being undefined. It does work however using call
and specifying this
yourself:
Promise.denodeify(o.aFunction).call(o);
To my knowledge there wouldn't be a way of working out what this
is supposed to be but maybe the API could be a bit nicer by accepting an optional parameter that would be used as this
.
Promise.denodeify(o, o.aFunction)();
Happy to submit a pull req with a fix if you agree with the proposed solution. Otherwise it'd good to update the docs to point out this potential issue as it'll probably catch out a lot of people using this to wrap third party functions.
Hello,
I upgraded to promise 4.0. This new version (with node.js) uses asap
to async the resolution instead of the previous next-tick.js.
I hit a problem of a starving event loop leading to the asap(task) never called in my server, in relation to node-sqlite3.
you can check TryGhost/node-sqlite3#184 (comment) for more information on where this comes from.
The problem does not appear when using setImmediate (reverting to promise 3.2).
I am trying to gather information as to how the problem should be fixed. Any idea will be welcome.
Promise.from(1).then(Promise.from(2)).then(Promise.from(3)).then(console.log);
gives 1.
Is that by design?
I had impression it should resolve to last .then as 3.
Would it be possible to make Promise.All
to take an object of promises and return a new one.
Here is almost the same example as in the doc.
Promise
.all({
a: Promise.resolve('a'),
b: 'b',
c: Promise.resolve('c')
})
.then(function (res) {
assert(res.a === 'a')
assert(res.b === 'b')
assert(res.c === 'c')
})
While writing a library to automatically wrap Node core methods to return promises, I came across this bug:
var Promise = require("promise");
var readFile = Promise.denodeify(require("fs").readFile);
// The callback here will never be called.
readFile("/etc/passwd", function(err, contents) {));
While this may be by design, and the method name alludes to, this is highly undesired behavior. I would expect that the intended behavior is to simply return a valid Promise and not break existing functionality.
Test and patch forthcoming.
You are still missing finally() in your library. Any plans to finally add it? :)
Please see the following discussion that's very relevant to this issue: tildeio/rsvp.js#373 (comment)
In the Readme.md
it is stated that a browserified version of this library is available at http://www.promisejs.org/implementations/promise/promise-3.2.0.js
This link is currently not working (anymore).
This is just not true, you should separate the pure spec implementation in one project and your custom .done, denodify etc. methods into another.
Its just weird to learn your code and then to recognize .done is actually not in spec and not in native implementations. This should be much more clear.
We may want to consider using native promises when available in the near future. We would still need to provide Promise.prototype.done
and the node.js extensions though.
We would have two options:
/lib/core.js
otherwise.We also have a few options when there is no built in promise constructor:
Promise
globally (in addition to exporting it). Effectively making this library a true polyfill but with some extensions.Promise
globally, but only add our special extensions to a copy that inherits from the globally defined Promse.I ran the latest tests from the A+ test suite. It reports 60 failures, but they're all the same thing: Not implementing §2.3.3.3 of the promise resolution procedure.
Here's the test I used, in case I have an error in the adapter: https://gist.github.com/tjcrowder/8912323
I also tried a simplified test case, which did seem to confirm the result: https://gist.github.com/tjcrowder/8912340 With that, I get the message saying we're resolving, but no calls to the then
method.
This is a significant improvement, and a non-breaking change.
I love then/promise and wants to use it in a JavaScript REST API client I am working on.
I need to support IE8 and was wondering what parts of es5-shim were really needed for then/promise?
Do you think we could make it old-browsers compatible with IE8 with little changes? Thanks
I can't find any documentation for the .catch()
method. Did i overlook it?
Inspired by this StackOverflow question: https://stackoverflow.com/questions/25409391/errors-in-a-promises-error-handler-go-missing
See discussion in #61
It's more of a question, because I don't quite understand the logic of the code below:
promise.resolve()
.then(function () {
console.log('then-1');
})
.then(function () {
console.log('then-2');
})
.then(function () {
console.log('then-3');
});
produces the following output:
then-1
then-2
then-3
as opposed to:
then-1
I mean, we do not resolve anything pass the first then
function, so why do we still get into every then
that follows? Please explain, 'cos I feel dumb right now :)
is there an ETA on this making it to an npm version patch?
asap 1.0.0 doesn't browserify well, see isaacs/dezalgo#1
Can you please consider adding bower support?
According to the Promises/A+ spec, http://promises-aplus.github.io/promises-spec/#point-60
If evaluating then produces an error, the promise must be rejected with the error (e). But when an error is thrown inside of then(), the error is lost because it calls reject(e), which calls _reject(e) which doesn't do anything. The error is lost to the world, at this point.
Ex:
do.something = new Promise(function(resolve, reject) {
resolve(val);
});
do.something.then(function(result) {
// Do something that causes an error
// ...
}, function(reason) {
console.log(reason); // I was hoping this would be called...
});
The problem is that the error which is thrown is lost. How can I capture that error and handle it appropriately without having to put the code inside its own try/catch.
The readme doesn't mention which browsers this library supports. Does it support IE9? What about IE8? What about obsolete IE (IE 6 + 7)? Old Safari? Mobile browsers?
For example if we had a get
module
module.exports = function get(promise, name) {
return promise.then(function(value){
return value[name]
})
}
Now that function works fine as a standalone that we can use with any valid promise like so
var get = require('then/get')
get(somePromiseObject, 'foo').then(doSomethingWithFoo)
What I'd like to see is a use
function that works like this:
var get = require('then/get')
var Promise = require('then/promise')
Promise.use('get', get)
new Promise(someResolver).get('foo').then(doSomethingWithFoo)
I'm a fan of this because it gives me the option of extending promises in my own applications, but still having access to all those great functions if I wanted to use them in a library and wanted to avoid extending the prototype
Maybe something along these lines
// maybe allow name to be optional and use fn.name by default
Promise.use = function(name, fn) {
Promise.prototype[name] = function() {
fn.apply(this, arguments)
}
}
Promise.prototype.use = function(name, fn) {
// make the extension usable in this promise chain only
}
The usage in document
Promise.all(Promise.resolve('a'), 'b', Promise.resolve('c'))
.then(function (res) {
assert(res[0] === 'a')
assert(res[1] === 'b')
assert(res[2] === 'c')
})
is actually not supported, according to source code of /lib/es6-extensions.js
.
As ES6 only support Promise.all(iterable)
usage, maybe it's README file which should be updated.
I'm interested in using this library purely for the superset features. I have an ES6 environment running with Traceur, so I do not need the polyfill.
I notice the extensions are in a separate module but they extend the polyfill’d Promise
object. In my case, this object has already been polyfill’d and is available at global.Promise
.
Should I be able to apply these extensions to my existing Promise
object?
Here's an example which confuses me.
var Promise = require('promise');
new Promise(function(res, rej) {
console.log(broken.invalid.imaginary);
});
When run this script exits without error and status 0
Intended behaviour? Perhaps I'm missing something?
function run() {
a().then(b).then(c);
}
function a() {
return new Promise(function (resolve) {
console.log('a()');
setTimeout(function () {
console.log('a resolved');
resolve();
}, 100);
});
}
function b() {
return new Promise(function (resolve) {
console.log('b()');
setTimeout(function () {
console.log('b resolved');
resolve();
}, 100);
});
}
function c() {
return new Promise(function (resolve) {
console.log('c()');
setTimeout(function () {
console.log('c resolved');
resolve();
}, 100);
});
}
output:
a()
a resolved
b()
c()
b resolved
c resolved
expected output:
a()
a resolved
b()
b resolved
c()
c resolved
I want to rewrite a library which using Q. I need it for the browser and using component, so I want to replace kriskowal/q with then/promise.
The code I want to rewrite uses Q.delay()
and Q.finally()
, do you know how I can rewrite it?
Just curious if it is feasible to define static method Promise.timer similar to Promise.all. It aims to create a promise of input promise to fulfill the promise within input timeout parameter in millisecond.
Promise.timer = (p, ms = env.promise.timeout) ->
return new Promise (fulfill, reject) ->
task = null
success = (result) ->
clearTimeout task
fulfill(result)
error = ->
reject 'timeout to complete the task'
task = setTimeout error, ms
p.then success, reject
In addition to that there are some errors that are very cryptic:
Example snippet:
TypeError: Cannot read property 'length' of null
at Promise._94
Are there any plans to enhance the UX?
I was wondering if I could change Promise to support something like bluebird's synchronous inspection. This would allow the user to inspect a promise to see if it's resolved and would not let them modify any internal values.
Originally I was going to do this as an extension but I think that'd I'd have to modify the lib/core.js
file to really support this. I'd be willing to write this myself, it wouldn't be difficult.
I can't find a changelog and I don't know if I should worry about changes from v5 to v6 since you upped the major version?
I was currently about to wrap the request module with denodeify()
, but the request()
returns two parameters in its response and denodeify()
only forwards the first parameter – therefore it doesn't work.
Is there a reason for denodeify()
to only return the first parameter? I think it could resolve the promise with them all in array if it finds that there are more than one response parameter.
That would make these two equal:
function callback (err, param1, param2) {
};
denodeify().then(function (result) {
var param1 = result[0]
, param2 = result[1];
});
At the moment a developer must know and remember to put promise.js before require.js in to avoid auto module registration.
A solution could be to Optionally registers as AMD module as they did in the latest underscore release. They used to do something similar to what promise does but it was removed in the 1.3.0 release.
Promise
is part of the ES6 proposal, this is why the following code cause an error, when esnext
is enabled in jshint config:
var Promise = require('promise');
^ Redefinition of 'Promise'.
Maybe you should change example codes, to avoid future problems/confusion.
I'd like to understand how conditional execution of promises is handled best.
I ended up developing these helpers but perhaps there is a better way??
https://github.com/colmsjo/promise-ifandor
Any suggestions are greatly appreciated!
Hey, I've written the following proposal here: https://gist.github.com/benjamingr/0237932cee84712951a2
I'd love your feedback.
Something strange seems to be reported after upgrading to 7.0.0: vitaly-t/pg-promise#14
Using http://benchmarkjs.com/ to test against Q (this should be way faster but I'm betting it isn't out of the box.
Could you add an explicit license file with the full text rather than just saying it's MIT?
Among other things, I've switched to using @kriskowal's ASAP as a replacement for our basic next-tick implementation. Running the benchmarks before and after gives:
In particular, the last 2 tests, which are the most realistic tests anyway, see enormous improvement. then.promise is now the fastest for the resolve-sequence
, and back very much in the game for the resolved-sequence
.
Hello everyone im new using promises and Promise and i was trying to implement some stuff according to the documentation, but im getting this output in console.
localpath\myprojectI\node_modules\promise\node_modules\asap\asap.js:45
throw e; ^
[object Object]
When im trying to run this code:
Following the documentation i did this, that maybe is totally wrong:
var getRequest = function(url){
return new Promise(function(resolve, reject){
request(url, function(e, res, body){
if(e){
reject(e);
}else{
if(res.statusCode == 200) resolve(body);
else reject({error: true, errorStatusCode: res.statusCode});
}
});
});
};
var info = function(user){
var url = 'http://someweb.com/api/';
return new Promise(function(resolve, reject){
getRequest(url.concat(user)).done(function(res){
try{
resolve(res);
}catch(ex){
reject(ex);
}
}, reject);
});
};
info('erick').done(function(res){
console.log(res);
});
It works perfect when the res.statusCode == 200 is true, but when for example the statusCode is 404 it shows in console just :
localpath\myprojectI\node_modules\promise\node_modules\asap\asap.js:45
throw e; ^
[object Object]
And i dont know what to do next. I know this could be basic but im new using promises.
Thank you for advance,
It doesn't actually work
Maybe some other stuff is missing?
Had to dig in the code to make sure it exists.
Would you accept a PR with a fix?
Hi, tell me how it is used in conjunction with https://www.npmjs.com/package/mysql
I need a method to back results
var tasks = null;
tasks = GetTasks();
//....
function GetTasks() {
return new Promise(function (resolve, reject) {
connection.query('SELECT * FROM tasks', function (err, rows) {
if (err)
reject(err);
else
resolve(rows);
});
});
}
I've been using promise in my every project, including this one: pg-promise, until I ran into the necessity of using promise.any()
logic in my test cases, so I had to use Bluebird for testing, while keeping Promise for the production, which is awkward.
And now that I find I need promise.any
in more than one case, it is becoming unfortunate that I have to move to Bluebird completely.
Please, add promise.any
, it is a very important promise function!
We need to implement the missing methods from http://www.html5rocks.com/en/tutorials/es6/promises/#toc-api and rename where appropriate.
I'm trying to just do a simple chaining of promises, by first pushing promises to an array and then do Promise.all(array).then(function(results) { console.log(results); })
. This used to work just fine in v6.x, but since upgrading to the latest version, it fails.
At the essence, what seems to differ from before is:
console.log(new Promise(function (resolve, reject) {
resolve();
}));
Previously this would log: { then: [Function] }
Now on version 7.0.1, this results in: { _32: 0, _8: null, _89: [] }
Did I miss a change in API or am I messing things up? :)
Using component with the latest release raises an error at runtime.
Uncaught Error: Failed to require "./lib/core.js" from "then-promise/index.js"
Version of component used was 0.19.9 in case that matters.
The one usage in Promise.all makes this library incompatible with ie8 - but only if called with an array of promises; it works fine if called with an argument list of promises.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.