Can Javascript Promises be created with a single parameter? - javascript

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

Related

Where is rejected property stored for a Promise in Javascript?

In the following code, the output clearly shows that rejected is within the created promise1 object. Yet when I look at MDN, there is no property indicating whether a promise is resolved or rejected. How does the program know whether a promise is accepted? Where is this information stored?
const promise1 = new Promise((resolve, reject) => {
throw 'Uh-oh!';
});
console.log(promise1); //Promise { <rejected> 'Uh-oh!' }
promise1.catch((error) => {
console.error(error);
});
There is no public API to check the Promise state, so there is no property that you could check.
Given the impossibility, you can try to do it on your own with any of these solutions:
https://ourcodeworld.com/articles/read/317/how-to-check-if-a-javascript-promise-has-been-fulfilled-rejected-or-resolved
https://github.com/nodejs/node/issues/40054#issuecomment-917641057
If I correctly get the question, you ask about the cases upon which JS itself rejects the promise. A promise is rejected when an error is returned from the callback function. In general case you (the programmer) define the conditions which mean success or error according to the code business. Based on what you need, you can either throw or reject the promise and this Q&A looks helpful.
But when a promise is gonna be used with a specific purpose, this behavior seems more clear, say when you use JS fetch api, there are solid situations in which the promise would be rejected.i.e. network disconnections or CORS errors. Here you can find a more detailed reply. These situations are those which are not biased towards any data transfer protocol such as HTTP.
Finally, here, you can find a pretty well explained pattern for designing your promise workflow.

Clarification of node.js + promises snippet

The accepted answer for How do I convert an existing callback API to promises? has this example:
function getUserDataAsync(userId){
return new Promise(function(resolve,reject){
getUserData(userId,resolve,reject);
});
}
Questions:
Shouldn't the body of Promise return something, not just call getUserData (at least in practical code, not as promise demonstration exercise)?
Is this particular Promise also a closure? It seems like it closes over userId, as getUserDataAsync creates and returns a new Promise instance using userId, but I want to be sure.
Shouldn't the body of Promise return something, not just call getUserData (at least in practical code, not as promise demonstration exercise)?
No, it doesn't have to. In fact, returning a value from the Promise constructor will have no effect. Only resolve and reject functions can fulfill a Promise.
Is this particular Promise also a closure? It seems like it closes over userId, as getUserDataAsync creates and returns a new Promise instance using userId, but I want to be sure.
Yes, the function passed to the Promise constructor closes over userId.
No, it shouldn't return something, because there is nothing to return at that point in time, hence the reason you are using a promise.
Yes.

How to reject (and properly use) Promises?

Short story:
Talking about Promises/A+, what is the proper way to reject a promise - throwing an error? But if I miss the catch - my whole app will blow!
How to use promisify and what are the benefits of it (maybe you'll need to read the longer version)?
Is .then(success, fail) really an anti-pattern and should I always use .then(success).catch(error)?
Longer version, described as real life problem (would love someone to read):
I have a library that uses Bluebird (A+ Promise implementation library), to fetch data from database (talking about Sequelize). Every query returns a result, but sometimes it's empty (tried to select something, but there wasn't any). The promise goes into the result function, because there is no reason for an error (not having results is not an error). Example:
Entity.find(1).then(function(result) {
// always ending here, despite result is {}
}).catch(function(error) {
// never ends here
});
I want to wrap this and check if the result is empty (can't check this everywhere in my code). I did this:
function findFirst() {
return Entity.find(1).then(function(result) {
if (result) { // add proper checks if needed
return result; // will invoke the success function
} else {
// I WANT TO INVOKE THE ERROR, HOW?! :)
}
}).catch(function(error) {
// never ends here
});
}
findFirst().then(function(result) {
// I HAVE a result
}).catch(function(error) {
// ERROR function - there's either sql error OR there is no result!
});
If you are still with me - I hope you will understand what's up. I want somehow to fire up the error function (where "ERROR function" is). The thing is - I don't know how. I've tried these things:
this.reject('reason'); // doesn't work, this is not a promise, Sequelize related
return new Error('reason'); // calls success function, with error argument
return false; // calls success function with false argument
throw new Error('reason'); // works, but if .catch is missing => BLOW!
As you can see by my comments (and per spec), throwing an error works well. But, there's a big but - if I miss the .catch statement, my whole app blows up.
Why I don't want this? Let's say I want to increment a counter in my database. I don't care about the result - I just make HTTP request.. So I can call incrementInDB(), which has the ability to return results (even for test reasons), so there is throw new Error if it failed. But since I don't care for response, sometimes I won't add .catch statement, right? But now - if I don't (on purpose or by fault) - I end up with your node app down.
I don't find this very nice. Is there any better way to work it out, or I just have to deal with it?
A friend of mine helped me out and I used a new promise to fix things up, like this:
function findFirst() {
var deferred = new Promise.pending(); // doesnt' matter if it's Bluebird or Q, just defer
Entity.find(1).then(function(result) {
if (result) { // add proper checks if needed
deferred.resolve(result);
} else {
deferred.reject('no result');
}
}).catch(function(error) {
deferred.reject('mysql error');
);
return deferred.promise; // return a promise, no matter of framework
}
Works like a charm! But I got into this: Promise Anti Patterns - wiki article written by Petka Antonov, creator of Bluebird (A+ implementation). It's explicitly said that this is wrong.
So my second question is - is it so? If yes - why? And what's the best way?
Thanks a lot for reading this, I hope someone will spent time to answer it for me :) I should add that I didn't want to depend too much on frameworks, so Sequelize and Bluebird are just things that I ended up working with. My problem is with Promises as a global, not with this particular frameworks.
Please ask only a single question per post :-)
Is .then(success, fail) really an anti-pattern and should I always use .then(success).catch(error)?
No. They just do different things, but once you know that you can choose the appropriate one.
How to use promisify and what are the benefits of it?
I think the Bluebird Promisification docs explain this pretty well - it's used to convert a callback api to one that returns promises.
Talking about Promises/A+, what is the proper way to reject a promise - throwing an error?
Yes, throwing an error is totally fine. Inside a then callback, you can throw and it will be caught automatically, resulting to the rejection of the result promise.
You can also use return Promise.reject(new Error(…));; both will have absolutely the same effect.
A friend of mine helped me out and I used a new promise to fix things up, like this: […]
No. You really shouldn't use that. Just use then and throw or return a rejected promise in there.
But if I miss the catch statement - my whole app will blow!
No, it won't. Notice that .catch() method is not a try catch statement - the error will already be caught where your then callback was invoked. It is then only passed to the catch callback as an argument, the .catch() call is not required to capture exceptions.
And when you miss .catch(), your app won't blow. All what happens is that you have a rejected promise laying around, the rest of your app won't be affected by this. You will get an unhandled rejection event, which can be dealt with globally.
Of course, that should not happen; every promise chain (not every promise instance) should be ended with a .catch() that handles errors appropriately. But you definitely don't need .catch() in every helper function, when it returns a promise to somewhere else then errors will usually be handled by the caller.
Talking about Promises/A+, what is the proper way to reject a promise - throwing an error? But if I miss the catch - my whole app will blow!
And if you use return codes to signal errors instead of exceptions, missing the check will cause subtle bugs and erratic behavior. Forgetting to handle errors is a bug, but having your app blow up in such an unfortunate case is more often better than letting it continue in corrupted state.
Debugging forgotten error code check that is only apparent by the application behaving weirdly at some unrelated-to-the-source-of-error place is easily many orders of magnitude more expensive than debugging a forgotten catch because you have the error message, source of error and stack trace. So if you want productivity in typical application development scenario, exceptions win by a pretty huge margin.
.then(success, fail)
This is usually signal that you are using promises as glorified callbacks where the callbacks are simply passed separately. This is obviously an anti-pattern as you will not get any benefits from using promises in this way. If that's not the case, even then you are just making your code slightly less readable compared to using .catch(), similar to how method(true, true, false) is much less readable than method({option1: true, option2: true, option3: false}).
How to use promisify and what are the benefits of it (maybe you'll need to read the longer version)?
Most modules only expose a callback interface, promisify turns a callback interface automatically into a promise interface. If you are writing such code manually (using deferred or new Promise), you are wasting your time.
So my second question is - is it so? If yes - why? And what's the best way?
The best way is to chain the promise:
function findFirst() {
return Entity.find(1).tap(function(result) {
if (!result) throw new Error("no result");
});
}
It's better because it's simpler, shorter, more readable and far less error-prone way to do exactly the same thing.

Alternative way to create a promise with q

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.

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