Alternative way to create a promise with q - javascript

I know how to create a promise in Kris Kowal's q with var defer = Q.defer();, calling defer.resolve(); and/or defer.reject() and return defer.promise. But reading the docs, it seem's there is an alternative way to create a promise...
From the docs:
Q.Promise(resolver)
Synchronously calls resolver(resolve, reject, notify) and
returns a promise whose state is controlled by the functions passed to
resolver. This is an alternative promise-creation API that has the
same power as the deferred concept, but without introducing another
conceptual entity.
If resolver throws an exception, the returned promise will be rejected
with that thrown exception as the rejection reason.
This is, what I've tried:
function () {
return Q.Promise(function (resolve, reject) {
(...do something...)
resolve(5); // or: reject(error);
});
}
But this doesn't work as expected!
Can someone give an example, how to use Q.Promise?
UPDATE:
Thanks for downvoting! I asked for an usage example, therefore a simple "you use it in a correct way" is more helpful! Btw: it fails silently and yes, I attached an error handler!
The reason, why the function is unnamed, is that I use it together with map and reduce to create a delayed chain of promises, but it seems, the resolver functions are never called... Therefore I asked for a (again) usage example...

Looking at your 2 examples, I'm guessing you are doing this:
var q = require('q');
Therefore Q.Promise won't work, but rather q.Promise will.

Related

Can Javascript Promises be created with a single parameter?

When we create a Promise(), the constructor expects two parameters: resolve and reject.
Can I create a Promise using only resolve?
let promise = new Promise((resolve) => {});
I've tried and it works. But, it is a good practice? The promise is expected to be resolved in all circumstances.
Yes, it's doable. If
you're sure the Promise will always resolve, or
there is no real way to detect if an error occurs (in which case a reject parameter wouldn't be used anyway)
then using only the resolve parameter is a reasonable possibility.
If there's any chance of an error - even an unexpected error - it'd be a good idea to use the reject parameter, though. Many errors are not expected, after all.
yes you can with
Promise.resolve(value);
refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

Could not understand the note with Promise.prototype.then() in MDN Document

I'm learning to convert my Node.js code style from callback to promise which seems to be the tendency and it has many advantages. To prevent the misunderstanding of the important points and benefits of the promise, I'm reading
document on MDN . I can understand Examples in this page, but I am not clear with the note that at the beginning of the document, it had mentioned :
Note: ... If the first argument is omitted or provided a non-function,
the new Promise that is created simply adopts the fulfillment state of
the Promise that then is called on (if it becomes fulfilled). If the
second argument is omitted or provided a non-function, the new Promise that
is created simply adopts the rejection state of the Promise that then is called
on (if it becomes rejected).
Sorry in advance if this is trivial.
Hope for the explanation with examples, thanks.
EDIT: Updated to better match the spec - see here and here.
The .then method calls one of two functions, depending on whether or not the Promise it's attached to has fulfilled or rejected. It then returns a new Promise based on the result of that call. This allows you to run different logic depending on whether or not a Promise was successful, and makes it possible to chain Promises together easily.
If you decide not to pass in one of those functions, however, it uses sensible defaults - which is what the note you posted is alluding to. It's probably a lot easier to demonstrate than to describe, though!
If you leave out the onRejected callback, like so:
myPromise.then(function (value) {
console.log("success!");
});
The result is the same as doing this:
myPromise.then(function (value) {
console.log("success!");
}, function (reason) {
throw reason;
});
If you leave out the onFulfilled callback, like so:
myPromise.then(null, function (reason) {
console.log("fail!");
});
The result is the same as:
myPromise.then(function (value) {
return value; // the same as returning Promise.resolve(value)
}, function (reason) {
console.log("fail!");
});
If you leave both out... it's basically pointless, but still:
myPromise.then();
This is effectively the same thing as:
myPromise.then(function (value) {
return value;
}, function (reason) {
throw reason;
});
Which is in turn, basically just:
myPromise
The other answers provide good explanations, but it might be easier to express this using the concept of skipping over.
If and when the promise fulfills, then the first argument to then is invoked (as long as it is a function); if and when the promise rejects, then the second argument to then is invoked (as long as it is there and is a function). In other cases, the .then is just skipped over.
Purists would object that it is incorrect to say the .then is "skipped over", and that what is really happening is that the .then creates a new promise which is equivalent to (or assumes the state of) the original promise. That's technically correct, but informally it's easier to talk and think about the .then getting "skipped".
Examples:
function log(v) { console.log("value", v); }
function err(e) { console.log("error", e); }
Promise.resolve(1).then(null, err).then(log);
^^^^^^^^^^^^^^^ "SKIPPED" (onFulfilled is null)
Promise.reject(1).then(log).catch(err);
^^^^^^^^^ "SKIPPED" (onRejected is not given)
For completeness, the corresponding behavior for catch is:
If and when the promise rejects, then the argument to catch is invoked (as long as it is a function). In other cases, the .catch is just skipped over.
Promise.resolve(1).catch(err).then(log);
^^^^^^^^^^ "SKIPPED" (promise did not reject)
If you think about it carefully, you will see that this all means that .then(null, handler) is exactly equivalent in every way to .catch(handler). So catch can be thought of as a kind of convenience routine.
But what's the point of allowing, but then ignoring, non-function handlers? Shouldn't they throw a TypeError or something instead? Actually, this is a "feature" which can be used as follows:
promise.then(isWednesday && wednesdayHandler)
If it's Wednesday, then this will evaluate to wednesdayHandler and we can do some special Wednesday processing. It it's not Wednesday, then this will evaluate to false, which is obviously not a function, so the whole then clause will be "skipped".
I don't have too much to add to this that the other answers don't already--just that I came to this question in the process of writing my own question about this, at which point SO miraculously suggested this one as a possible duplicate (when it did not come up in my previous search attempts).
Anyways the current documentation on MDN on the parameters to Promise.prototype.then have changed a bit since the OP and I think are still confusing, if not even moreso than before, so I thought I would add a follow-up answer concerning the current documentation which reads:
onFulfilled Optional
A Function called if the Promise is fulfilled. This function has one argument, the fulfillment value. If it is not a function, it is internally replaced with an "Identity" function (it returns the received argument).
What's confusing about this wording is it's not totally clear what is the antecedent of "received argument". Without already being familiar with the details of the Promises spec, one could read this as the "identity" function returning the argument received by the then() call. I.e. that something like this:
let promise = new Promise((resolve, reject) => resolve("value"));
let chained = promise.then("new value");
is equivalent to this:
let promise = new Promise((resolve, reject) => resolve("value"));
let chained = promise.then(() => "new_value");
so that the value resolved from chained is "new_value".
When in fact, "received value" refers to the resolved value of the original promise that .then() was chained from, i.e.:
let promise = new Promise((resolve, reject) => resolve("value"));
let chained = promise.then(() => "value");
So writing promise.then("not_a_callable") completely ignores "not a callable" and is resolved to the value that fulfilled the original promise, whatever it happens to have been.
Personally, I think this confusing behavior, but it is what it is.

Why does the Promise constructor need an executor?

When using Promises, why can't triggers for resolve and reject be defined elsewhere in the codebase?
I don't understand why resolve and reject logic should be localized where the promise is declared. Is this an oversight, or is there a benefit to mandating the executor parameter?
I believe the executor function should be optional, and that its existence should determine whether the promise encapsulates resolution or not. The promise would be much more extensible without such mandates, since you don't have to initiate async right away. The promise should also be resettable. It's a 1 shot switch, 1 or 0, resolve() or reject(). There are a multitude of parallel and sequential outcomes that can be attached: promise.then(parallel1) and promise.then(parallel2) and also promise.then(seq1).then(seq2) but reference-privileged players cannot resolve/reject INTO the switch
You can construct a tree of outcomes at a later time, but you can't alter them, nor can you alter the roots (input triggers)
Honestly, the tree of sequential outcomes should be edittable as well.. say you want to splice out one step and do something else instead, after you've declared many promise chains. It doesn't make sense to reconstruct the promise and every sequential function, especially since you can't even reject or destroy the promise either...
This is called the revealing constructor pattern coined by Domenic.
Basically, the idea is to give you access to parts of an object while that object is not fully constructed yet. Quoting Domenic:
I call this the revealing constructor pattern because the Promise constructor is revealing its internal capabilities, but only to the code that constructs the promise in question. The ability to resolve or reject the promise is only revealed to the constructing code, and is crucially not revealed to anyone using the promise. So if we hand off p to another consumer, say
The past
Initially, promises worked with deferred objects, this is true in the Twisted promises JavaScript promises originated in. This is still true (but often deprecated) in older implementations like Angular's $q, Q, jQuery and old versions of bluebird.
The API went something like:
var d = Deferred();
d.resolve();
d.reject();
d.promise; // the actual promise
It worked, but it had a problem. Deferreds and the promise constructor are typically used for converting non-promise APIs to promises. There is a "famous" problem in JavaScript called Zalgo - basically, it means that an API must be synchronous or asynchronous but never both at once.
The thing is - with deferreds it's possible to do something like:
function request(param) {
var d = Deferred();
var options = JSON.parse(param);
d.ajax(function(err, value) {
if(err) d.reject(err);
else d.resolve(value);
});
}
There is a hidden subtle bug here - if param is not a valid JSON this function throws synchronously, meaning that I have to wrap every promise returning function in both a } catch (e) { and a .catch(e => to catch all errors.
The promise constructor catches such exceptions and converts them to rejections which means you never have to worry about synchronous exceptions vs asynchronous ones with promises. (It guards you on the other side by always executing then callbacks "in the next tick").
In addition, it also required an extra type every developer has to learn about where the promise constructor does not which is pretty nice.
FYI, if you're dying to use the deferred interface rather than the Promise executor interface despite all the good reasons against the deferred interface, you can code one trivially once and then use it everywhere (personally I think it's a bad idea to code this way, but your volume of questions on this topic suggests you think differently, so here it is):
function Deferred() {
var self = this;
var p = this.promise = new Promise(function(resolve, reject) {
self.resolve = resolve;
self.reject = reject;
});
this.then = p.then.bind(p);
this.catch = p.catch.bind(p);
if (p.finally) {
this.finally = p.finally.bind(p);
}
}
Now, you can use the interface you seem to be asking for:
var d = new Deferred();
d.resolve();
d.reject();
d.promise; // the actual promise
d.then(...) // can use .then() on either the Deferred or the Promise
d.promise.then(...)
Here a slightly more compact ES6 version:
function Deferred() {
const p = this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
this.then = p.then.bind(p);
this.catch = p.catch.bind(p);
if (p.finally) {
this.finally = p.finally.bind(p);
}
}
Or, you can do what you asked for in your question using this Deferred() constructor:
var request = new Deferred();
request.resolve();
request.then(handleSuccess, handleError);
But, it has the downsides pointed out by Benjamin and is not considered the best way to code promises.

JavaScript native Promise execute callback on both results

Is there any way to execute callback on both results of Promise object?
For example I want to make some cleanup logic after execution of xhr request. So I need to do something like this:
var cleanUp = function() { something.here(); }
myLib.makeXhr().then(cleanUp,cleanUp);
In jquery Defered for example i can use method always():
myLib.makeXhr().always(function() { something.here(); });
Does Promise support something like this?
No, there is none. It was discussed but the spec is minimal. It doesn't include a bunch of other functionality. It's designed to interoperate well with library promises and to provide simple functionality.
Here is a correct polyfill of that proposal originally made by StefPanner.
Moreover, I disagree with the current now deleted answers adding it themselves because they're all doing it wrong (as an enumerable property - no fun). Even if we ignore what it does to the return values and error state of the returned promise. The intended way to extend native promises is by subclassing them, sadly, no browsers support this yet so we'll have to wait.
Instead of messing with native prototypes, we should use a different pattern:
openDb().then(foo).then(bar).finally(close).then(more);
Is susceptible to us forgetting to call close, even if we open it 100 times in our app, forgetting to close it even once can still be devastating. On the other hand - we can use the disposer pattern which some promise libraries provide built in ourselves:
openDb(function(db){
return foo(db).then(bar);// chain here
}).then(more);
Basically - this pattern means instead of having openDB return a promise - we have it take a function and return a promise, when the function is run, if it returns a promise we wait for that promise to resolve. It looks something like:
function openDb(withDb){
return justOpenWithoutCleanUp().
then(withDb).
then(clean, function(e){ clean(); throw e; }); // note the rethrow
}
Promise object supports 'always'.
For eg:
var oPromise= jQuery.ajax({
url:YOUR_URL
}).always(function(){
YOUR_CLEAN_UP_METHOD();
})

Understanding promises in Node.js

From what I have understood there are three ways of calling asynchronous code:
Events, e.g. request.on("event", callback);
Callbacks, e.g. fs.open(path, flags, mode, callback);
Promises
I found the node-promise library but I don’t get it.
Could someone explain what promises are all about and why I should use it?
Also, why was it removed from Node.js?
Since this question still has many views (like mine) I wanted to point out that:
node-promise looks rather dead to me (last commit was about 1 year ago) and contains nearly no tests.
The futures module looks very bloated to me and is badly documented (and I think that the naming conventions are just bad)
The best way to go seems to be the q framework, which is both active and well-documented.
Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.
The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete).
By removing them from the core node.js, it created possibility of building up modules with different implementations of promises that can sit on top of the core. Some of these are node-promise and futures.
A promise is a "thing" which represents the "eventual" results of an operation so to speak. The point to note here is that, it abstracts away the details of when something happens and allows you to focus on what should happen after that something happens. This will result in clean, maintainable code where instead of having a callback inside a callback inside a callback, your code will look somewhat like:
var request = new Promise(function(resolve, reject) {
//do an ajax call here. or a database request or whatever.
//depending on its results, either call resolve(value) or reject(error)
//where value is the thing which the operation's successful execution returns and
//error is the thing which the operation's failure returns.
});
request.then(function successHandler(result) {
//do something with the result
}, function failureHandler(error) {
//handle
});
The promises' spec states that a promise's
then
method should return a new promise that is fulfilled when the given successHandler or the failureHandler callback is finished. This means that you can chain together promises when you have a set of asynchronous tasks that need to be performed and be assured that the sequencing of operations is guaranteed just as if you had used callbacks. So instead of passing a callback inside a callback inside a callback, the code with chained promises looks like:
var doStuff = firstAsyncFunction(url) {
return new Promise(function(resolve, reject) {
$.ajax({
url: url,
success: function(data) {
resolve(data);
},
error: function(err) {
reject(err);
}
});
};
doStuff
.then(secondAsyncFunction) //returns a promise
.then(thirdAsyncFunction); //returns a promise
To know more about promises and why they are super cool, checkout Domenic's blog : http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/
This new tutorial on Promises from the author of PouchDB is probably the best I've seen anywhere. It wisely covers the classic rookie mistakes showing you correct usage patterns and even a few anti-patterns that are still commonly used - even in other tutorials!!
http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html
Enjoy!
PS I didn't answer some other parts of this question as they've been well covered by others.
Mike Taulty has a series of videos, each of them less than ten minutes long, describing how the WinJS Promise library works.
These videos are quite informative, and Mike manages to show the power of the Promise API with a few well-chosen code examples.
var twitterUrl = "http://search.twitter.com/search.json?q=windows";
var promise = WinJS.xhr({ url: twitterUrl });
promise = promise.then(
function (xhr) {
},
function (xhr) {
// handle error
});
The treatment of how exceptions are dealt with is particularly good.
In spite of the WinJs references, this is a general interest video series, because the Promise API is broadly similar across its many implementations.
RSVP is a lightweight Promise implementation that passes the Promise/A+ test suite. I quite like the API, because it is similar in style to the WinJS interface.
Update Apr-2014
Incidentally, the WinJS library is now open source.
Another advantage of promises is that error handling and exception throwing and catching is much better than trying to handle that with callbacks.
The bluebird library implements promises and gives you great long stack traces, is very fast, and warns about uncaught errors. It also is faster and uses less memory than the other promise libraries, according to http://bluebirdjs.com/docs/benchmarks.html
What exactly is a Promise ?
A promise is simply an object which represents the result of an async operation. A promise can be in any of the following 3 states :
pending :: This is the initial state, means the promise is neither fulfilled nor rejected.
fulfilled :: This means the promise has been fulfilled, means the value represented by promise is ready to be used.
rejected :: This means the operations failed and hence can't fulfill the promise.
Apart from the states, there are three important entities associated to promises which we really need to understand
executor function :: executor function defines the async operation which needs to be performed and whose result is represented by the promise. It starts execution as soon as the promise object is initialized.
resolve :: resolve is a parameters passed to the executor function , and in case the executor runs successfully then this resolve is called passing the result.
reject :: reject is another parameter passed to the executor function , and it is used when the executor function fails. The failure reason can be passed to the reject.
So whenever we create a promise object, we've to provide Executor, Resolve and Reject.
Reference :: Promises
I've been also looking into promises in node.js recently. To date the when.js seems to be the way to go due to its speed and resource use, but the documentation on q.js gave me a lot better understanding. So use when.js but the q.js docs to understand the subject.
From the q.js readme on github:
If a function cannot return a value or throw an exception without
blocking, it can return a promise instead. A promise is an object that
represents the return value or the thrown exception that the function
may eventually provide. A promise can also be used as a proxy for a
remote object to overcome latency.
Promise object represents the completion or failure of an asynchronous operation.
So in order to implement a promise, you need two parts:-
1.Creating Promise:
The promise constructor accepts a function called an executor that has
2 parameters resolve and reject.
function example(){
return new Promise (function(resolve , reject){ //return promise object
if(success){
resolve('success'); //onFullfiled
}else{
reject('error'); //onRejected
}
})
}
2.Handling Promise:
Promise object has 3 methods to handle promise objects:-
1.Promise.prototype.catch(onRejected)
2.Promise.prototype.then(onFullfiled)
3.Promise.prototype.finally(onFullfiled,onRejected)
example.then((data) =>{
//handles resolved data
console.log(data); //prints success
}).catch((err) => {
//handles rejected error
console.log(err); //prints error
})

Categories