I came across promises as I am going through my journey on learning AngularJS and it has been good so far. Now, I wanted to learn more about using AngularJS optional library resource.js. However, I came across examples that confused me a lot. For example, the promise skeleton is basically like this example.
//post method to server
$http.post('api/school',newStudent).then(fetchStudents).then(function(response){
//do something
}, function(error){
//do something
});
and another example like this assuming we have a List factory
List.save(self.newStudent).$promise.then(fetchStudents).then(function(){
self.newStudent = {};
});
So my question is why the use of $promise? What is the use of it? It was not really explained in the book I am using and I am confuse on when to use it or not. Any clear explanation will be appreciated. Thanks
A service that helps you run functions asynchronously, and use their
return values (or exceptions) when they are done processing
Promises provide a simpler alternative for executing, composing, and managing asynchronous operations when compared to traditional callback-based approaches. They also allow you to handle asynchronous errors using approaches that are similar to synchronous try/catch.
Read more about it at :
https://docs.angularjs.org/api/ng/service/$q
http://haroldrv.com/2015/02/understanding-angularjs-q-service-and-promises/
http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls
Related
How to know what all methods in mongoDb has an inbuilt promise in it.
eg: "updateOne() , findOne()" these methods have inbuilt promises and and we can access the response using ".then" but for lots of other mongoDB methods lack this feature how can we be sure of which methods dont have inbuilt promise in them?
eg: "find()" has no inbuilt promise so we cannott perform "find().then((response)=>{})" this will give an error.
Whereas "findOne().then((response)=>{})" will work without any issue.
This is inconsistent across the NodeJS MongoDB driver as some methods return more complex objects for manipulating the returned values. For example, .find() returns a FindCursor object which can be used to iterate over results by calling .next() repeatedly.
I would recommend referring the MongoDB documentation for the NodeJS driver (found here, or common usage examples are here) rather frequently. The documentation is reasonably extensive and should help with issues like this.
You can also consider using TypeScript, which I have personally found helpful for cases such as this because you can easily tell what type of object is returned from a function/method call.
I would recommend referring the MongoDB documentation for the NodeJS driver (found here, or common usage examples are here) rather frequently. The documentation is reasonably extensive and should help with issues like this
There is some inconsistency over the find method in MongoDB native driver in node Js. This is because the reason that the finds method returns a cursor. So what we could do here is convert that to an array using the toArray() method.
The best solution here would be to use async await over promise chaining.
This would provide us with a cleaner and easier syntax to work with.
Eg :
Let's say we want to find all the products in the product collection. Below is a function for doing exactly that.
const findAll=async(userId)=>{
const userData= await db.products.find().toArray();
console.log(userData);
return userData;
}
Upon calling the above function we would get all the products in the product collection. Just by looking at the code, we could see that it provides a more readable syntax than chaining promises all over.
Can anyone help me understand the function of NodeJS and performance impact for the below scenario.
a. Making the request to Rest API end point "/api/XXX". In this request, i am returning the response triggering the asynchronous function like below.
function update(req, res) {
executeUpdate(req.body); //Asynchronous function
res.send(200);
}
b. In this, I send the response back without waiting for the function to complete and this function executing four mongodb updates of different collection.
Questions:
As I read, the NodeJS works on the single thread, how this
asynchronous function is executing?
If there are multiple requests for same end point, how will be the
performance impact of NodeJS?
How exactly the NodeJS handles the asynchronous function of each
request, because as the NodeJS is runs on the single thread, is there
any possibility of the memory issue?
In short, it depends on what you are doing in your function.
The synchronous functions in node are executed on main thread, thus,
they will not preempt and execute until end of the function or until
return statement is encountered.
The async functions, on the other hand, are removed from main thread,
and will only be executed when async tasks are completed on a
separate worker thread.
There are, I think, two different parts in the answer to your question.
Actual Performance - which includes CPU & memory performance. It also obviously includes speed.
Understanding as the previous poster said, Sync and Async.
In dealing with #1 - actual performance the real only way to test it is to create or use a testing environment on your code. In a rudimentary way based upon the system you are using you can view some of the information in top (linux) or Glances will give you a basic idea of performance, but in order to know exactly what is going on you will need to apply some of the various testing environments or writing your own tests.
Approaching #2 - It is not only sync and async processes you have to understand, but also the ramifications of both. This includes the use of callbacks and promises.
It really all depends on the current process you are attempting to code. For instance, many Node programmers seem to prefer using promises when they make calls to MongoDB, especially when one requires more than one call based upon the return of the cursor.
There is really no written-in-stone formula for when you use sync or async processes. Avoiding callback hell is something all Node programmers try to do. Catching errors etc. is something you always need to be careful about. As I said some programmers will always opt for Promises or Async when dealing with returns of data. The famous Async library coupled with Bluebird are the choice of many for certain scenarios.
All that being said, and remember your question is general and therefore so is my answer, in order to properly know the implications on your performance, in memory, cpu and speed as well as in return of information or passing to the browser, it is a good idea to understand as best as you can sync, async, callbacks, promises and error catching. You will discover certain situations are great for sync (and much faster), while others do require async and/or promises.
Hope this helps somewhat.
I have seen different ways of doing multiple dependent ajax synchronous call. Two of which is being widely adopted is the jquery defer method and callback on success.
My question is:
1) What is the advantage of using one over another?
2) In what situation is one is preferred over another?
3) Is there any other better method than these 2?
// jquery defer method
var defer = $.when(
$.get('ajax_call_1');
);
defer.done(function () {
$.get('ajax_call_2');
});
// callback on success
$(function(){
$.ajax({
url:'/ajax_call_1',
data: { },
success: function(data){
$.get('ajax_call_2');
}
});
}
});
Some reasons to use Promises over Callbacks:
Much simpler to sequence multiple asynchronous operations.
Much simpler to build conditional logic involving multiple asynchronous operations.
Much simpler to do robust error handling involving multiple asynchronous operations.
Much simpler to build reusable asynchronous interfaces.
Much simpler to interface with other asynchronous interfaces.
Much simpler to deal with exceptions that might occur deep in asynchronous code that would otherwise cause silent failure
In your question, the simplest way to sequence jQuery Ajax calls and catch all possible errors is to use the natural promises returned from $.ajax() and chain them:
$.get('ajax_call_1').then(function(value) {
return $.get('ajax_call_2');
}).then(function(result) {
// success with both here
}, function(err) {
// error with one of them here
});
Or, with no error handling like in your example:
$.get('ajax_call_1').then(function(value) {
$.get('ajax_call_2');
})
There is no reason to use this construct here:
// jquery defer method
var defer = $.when(
$.get('ajax_call_1');
);
because $.get() already returns a promise so there is no need to use $.when() to just create yet another promise. $.when() is useful when you have more than one promise and you want to know when all of them are done. For one promise, you just use it directly - no reason to use $.when() with a single promise.
You can do it your second way:
// callback on success
$.ajax({
url:'/ajax_call_1',
data: { },
success: function(data){
$.get('ajax_call_2');
}
});
As this is just the non-promise way of coding with nested callbacks. The major disadvantage is that propagation of errors and sequencing multiple operations gets messy and difficult when not using promises. In just this simple example, try to get the error from either of the ajax calls back to the caller. It takes a lot of extra code to do that. My promise example above propagates all errors back to the caller for you.
As for your specific questions:
1) What is the advantage of using one over another?
You're basically asking why use promises over nested callbacks. There are hundreds of articles on the advantages of using promises. I will see if I can find one or two, but a Google search for "why promises vs. callbacks" should get you started on some reading.
What’s so great about JavaScript Promises?
Staying Sane with Asynchronous Programming
Why Am I Switching to Promises
2) In what situation is one is preferred over another?
I know of no reason why plain nested callbacks is preferred over using promises. Once you have learned promises, you will pretty much always find them a better way to code. The only reason I would not use promises is if I was trying to make code that was compatible with old browsers that did not have promises and even then, I'd probably just include a polyfill so that promises were supported.
3) Is there any other better method than these 2?
Yes, see my first code example.
P.S. Note that I choose to only use .then() with jQuery promises because that is the ES6 promise standard and it will make it easier in the future when jQuery transitions its promises to be more standards-compatible (which they are working on). Your code will also be more consistent when interfacing with other sources of promises that do use the standard.
P.P.S. Promises are one-shot devices. They either resolve or reject once and only once. If you are trying to get multiple notifications from some source, then promises are not built for that. An event emitter or a publish/subscribe system might be a better match for that type of problem.
This question already has answers here:
Javascript: How to determine whether to promisefy a function?
(2 answers)
Closed 4 years ago.
I'm getting into generators and promises now and I've kind of gotten the handle of how they work. Now it's time to make my own functions which utilize these. There are guides out there explaining how to make them and what they are for but however they rarely discuss the appropriate times when one should be used.
I know this mainly has to lie with promises as generators just help the code writing look synchronous (among other things).
So my question is: When should I and when should I not promisify a function I have?
From my understanding if the cpu is being utilized 100% by the function then I should NOT promisify as there is no point.
If the cpu is being blocked and is waiting for something external such as waiting for something to download then I guess I should promisify that function.
Promises should be used when you have asynchronous operations that you want to execute in a sequence. Operations that are costly, like writing to a file/db, making a request to another service, so forth, usually have an asynchronous api, since doing those synchronously would block your single-threaded javascript application. In those cases, you either use something like promises for a cleaner code, you use named functions and explicitly call them one after the other as callbacks or you don't use anything and have yourself a pyramid of doom full of callbacks.
So, imagine you want to get the user data from the token you recieve in the http request, then get all the posts regarding him, and get a special holiday offer from one of your other services that you wanna stick in there with the request. With promises, you could do something like
router.get('/activities', function(req, res){
userRepo.findByToken(token).then(checkForOffer).then(activityRepo.getUserPosts).then(function(composite){
res.send({activities: composite.activities, offer: composite.offer});
}).fail(function(err){
//handle the error
});
})
This post paint a clearer picture of how and when you should use promises.
Lately a colleague and I have had some disagreements on the "right" way to implement Cucumber step definitions using Protractor and Chai as Promised. Our contention comes from a mutual lack of understanding of precisely what is going with promise resolution in the context of Cucumber.
We're testing against an AngularJS application, so resolving promises and asynchronous behavior is a necessary evil. The biggest problem we've had is forcing synchronous test behavior and getting Cucumber to wait on promises between step definitions. In some cases, we've observed situations such that Cucumber seems to plow straight through step definitions before Webdriver even executes them. Our solutions to this problem vary...
Consider the hypothetical scenario:
Scenario: When a user logs in, they should see search form
Given a user exists in the system
When the user logs into the application
Then the search form should be displayed
Most of the confusion originates in the Then step. In this example the definition should assert that all fields for the search form exist on the page, meaning multiple isPresent() checks.
From the documentation and examples I was able to find, I felt the assertion should look something like this:
this.Then(/the search form should be displayed/, function(next) {
expect(element(by.model('searchTerms')).isPresent()).to.eventually.be.true;
expect(element(by.model('optionsBox')).isPresent()).to.eventually.be.true;
expect(element(by.button('Run Search')).isPresent()).to.eventually.be.true.and.notify(next);
});
However, my colleague contends that in order to satisfy promise resolution, you need to chain your expects with then() like this:
this.Then(/the search form should be displayed/, function(next) {
element(by.model('searchTerms')).isPresent().then(function(result) {
expect(result).to.be.true;
}).then(function() {
element(by.model('optionsBox')).isPresent().then(function(result) {
expect(result).to.be.true;
}).then(function() {
element(by.button('Run Search')).isPresent().then(function(result) {
expect(result).to.be.true;
next;
});
});
});
});
The latter feels really wrong to me, but I don't really know if the former is correct either. The way I understand eventually() is that it works similarly to then(), in that it waits for the promise to resolve before moving on. I would expect the former example to wait on each expect() call in order, and then call next() through notify() in the final expect() to signal to cucumber to move on to the next step.
To add even more confusion, I've observed other colleagues write their expects like this:
expect(some_element).to.eventually.be.true.then(function() {
expect(some_other_element).to.eventually.be.true.then(function() {
expect(third_element).to.eventually.be.true.then(function() {
next();
});
});
});
So the questions I think I'm alluding to are:
Is any of the above even kinda right?
What does eventually() really do? Does it force synchronous behavior like then()?
What does and.notify(next) really do? Is it different from calling next() inside of a then()?
Is there a best practices guide out there that we haven't found yet that gives more clarity on any of this?
Many thanks in advance.
Your feeling was correct, your colleague was wrong (though it was a reasonable mistake!). Protractor automatically waits for one WebDriver command to resolve before running a second. So in your second code block, element(by.button('Run Search')).isPresent() will not resolve until both element(by.model('optionsBox')).isPresent() and element(by.model('searchTerms')).isPresent() are done.
eventually resolves promises. An explanation is here: https://stackoverflow.com/a/30790425/1432449
I do not believe it's different from putting next() inside of then()
I do not believe there is a best practices guide. Cucumber is not a core focus of the Protractor team, and support for it is largely provided by the community on github. If you or someone you know would like to write a best practices guide, we (the protractor team) would welcome a PR!
What works for me is this - The function below searches for something that will always equal true - in the case the existence of a html tag. I call this function at the end of each test, passing in the callback
function callbackWhenDone(callback) {
browser.wait(EC.presenceOf(element(by.css('html'))))
.then(function () {callback();})
}
This is the usage in a simple test:
this.Given(/^I go on "([^"]*)"$/, function (arg1, callback) {
browser.get('/' + arg1);
callbackWhenDone(callback);
});
A bit of a hack I know but it gets the job done and looks pretty clean when used everywhere