the argument of the promise object's method then()'s callback function - angularjs

I am new to angular, I did some research but still cannot find an answer...,
I have the following code:
promiseB = promiseA.then(function(result) {
return result + 1;
});
Why we can use result as the argument of the callback function? How the returned stuff of promiseA becomes result ?
Thanks everyone!

A promise is simply an object used to represent the pending activity, don't confuse it with the result of that activity.
The resolved value is passed to the success callback that was given to the .then() method. If promises are chained together then the value returned from that callback becomes the value passed to the next .then() (or if the value returned is also a promise the resolution of that promise is passed to the next .then()).
So in your particular example we don't know where result came from: whatever created promiseA simply ensured it resolved with that value. However we do know that promiseB will resolve with the value result+1 because that's what you returned.

When promiseA completes ("resolves"), it will call the function that you pass to the then() function, and pass the result into that function. So let's say I had a promise that is requesting information from a database query. Let's say it's going to (eventually) give me the phone number for a user. I'd set up my code to print that out like this:
myPromise.then(function(phoneNum) {
console.log(phoneNum);
});
The reason we can't just say var result = myPromise() is because a promise executes in a different flow that the rest of the code. We need to set up a function to handle the result when it's done

Check how using the $q service you can defer the promise returned and process in sucesives callbacks, the defer.promiseit's the key.
var promiseB = myService.response().then(function(result){
var defer = $q.defer();
defer.resolve(result);
return defer.promise;
});
promiseB.then(function(result){
console.log("In promise B ===>", result);
});
check this codepen: http://codepen.io/gpincheiraa/pen/ONjMrR?editors=0010

Related

Asynchronous call defer and promise chain

I stuck with ashync call chain. I tried google but couldn't found exact answer.
requirement is I have a method
callApi(){
I am calling 4 service that all are asynchronous.
I want to chain all the asynchronous calls so that I can do
defer.resolve only when all request are done
}
Any help would be great help.
Thanks in Advance.
You can just use $q.all(). It takes an array of promises and returns a promise, that will resolve when all promises in that array have resolved.
Example:
function callMultipleServices() {
return $q.all([
//Just some random functions returning promises...
someAsyncService(),
$http.get('http://google.de'),
someOtherAsyncService()
]) //.then(function(resultArray) { return doSomethingWith(resultArray) })
}
The returned promise will resolve with an array, containing the resolved values of the promises you passed in. If you want your promise to return a single value that is somehow derived from the service results, just add a .then that takes the results and somehow calculates your final promise result (as in the comment above)

Angular and Meteor flicker on page load

I had an issue with and angular-meteor project flickering every time a state using the campaigns subscription, would load. By flickering, I mean the data was there, then it would go away and come back a half second later.
I added this to the resolve property of the state (using ui-router):
campaigns: ($q) => {
var deferred = $q.defer();
Meteor.subscribe('campaigns', {
onReady: deferred.resolve,
onStop: deferred.reject
});
return deferred.promise;
}
The flickering stopped, but I don't really understand this code. Can someone who understand angular break this resolve/defer situation down?
Just not sure why it worked. thanks.
$q is angular's implementation of promises.
in a very itty bitty nutshell, a promise has two callbacks that resolve when data is returned; a resolve function if the call succeeds and a reject if the call fails. whatever data it gets will be passed into these functions (essentially doing deferred.resolve(data) or deferred.reject(error)) . $q.defer() allows us to assign the resolution/rejections later.
meteor's subscribe function takes a few arguments. the string name of the collection, a function that returns an array of arguments to be passed to the collection, and an object/function. the object part of the final argument expects an "onReady" and "onStop" functions, and will execute those functions and pass along any data it gets. we pass in our callbacks here.
finally, we return the promise. resolve.campaigns will be a promise, which we can get the values from using the .then(successCallback, failureCallback) call. meteor handles this behind the scenes.

AngularJS - Promise vs then?

I have 2 questions -
1) What is the difference between the "success" and "then"?
example - $http.get(url).then vs $http.get(url).success?
2) A promise means something that would be executed in the future, fine. I am not able to wrap my head on how this is difference from a function call. a promise call is executed when we make call using "$q.defer.resolve()". Isn't this a function call? so why can't this be a normal function, and executed with any other function call like foo()? Am i missing something special that a promise does!! ?
What is the difference between the "success" and "then"?
then() takes a single argument: the http response object. success() takes 4 arguments: the data of the response, the status of the response, the headers of the response, and the http config object. success() is thus easier to use when all you care about is the data returned. As said by New Dev, the returned value is different: then() returns a new promise for whatever is returned from its callback and allows you to return a new value and thus build a promise chain, whereas success() returns the original promise.
A promise means something that would be executed in the future
No, not really. A promise is the result of something you execute now, but for which the result is not immediately available. Since JavaScript is single-threaded, you can't just block and wait for the result, because that would completely freeze the application. So you just register a callback function that will be called, asynchronously, when the result is available. For example:
$http.get('/some/url')
immediately sends an HTTP request. But to get the result, we need to wait for the bytes to travel to the server, for the server to handle the request and send back a response, and for the response to travel to the browser. This could take several seconds. So what $http.get() returns immediately is a promise: i.e. an object which represents a future result (or, once the result has been received, a result that was once future).
.then returns a new promise.
.success returns the original promise. Another difference is that .success gets the response.data as an input parameter, whereas .then gets the response.
This is how it's implemented:
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
You could use .success (and .error) to handle the respective outcome of $http, but without the ability to modify the data or to reject a promise (with return $q.reject()) given to the eventual consumer of the $http promise.
Here's an illustrative example of when one may use .success vs/with .then:
return {
getData: function(p1){
return $http.get(url, {p1: p1})
.success($log.log) // can use generic functions since there is
.error($log.error) // no requirement to return data
.then(function(response){
// here can massage the data into the output format
return response.data;
});
};
I recommend always using .then since it returns a new promise without .success and .error handlers; this avoids the chance of the API consumer using the $http-specific .success/.error thus inadvertently making the assumption that $http was used under the covers.

AngularJs chaining promisses and using notify

When I have multiple promises and resolve them one by one I can easily get notifications from each promise while it is being resolved.
However it seems that when I chain promises or use the all() method then some notifications are getting lost. I am wondering why this is the case.
Here is an example. Lets say I have two async functions that return a promise, do some work and while doing this they call notify one or more times:
function returnsSomePromise1() {...; setTimeout(...); return promise;}
function returnsSomePromise2() {...; setTimeout(...); return promise;}
Now I have three options to resolve the promises:
var promise1 = returnsSomePromise1();
var promise2 = returnsSomePromise2();
//Option 1: Resolve separate
promise1.then(...);
promise2.then(...);
//Option 2: Resolve chained
promise1.then(promise2).then(...);
//Option 3: Resolve with all()
$q.all([promise1, promise2]).then(...);
In each then function I attach a simple function to log the notifications to the console:
.then(..., ..., function(update) { console.log(update); });
Now I find it interesting that all three options yield different results when it comes to notify. The first one prints all notifications of each async operation. The second option only prints the notifications of the first promise, the last option using the all() method does not print any notifications at all.
Can anyone explain what is causing these differences and if it is possible to get notifications when using $q.all()?
Option 1 will fire the promises in parallel, they will be resolved individually. If you want to do something after both have resolved you would need to add extra logic using this option
Option 2 will fire the promises one after the other. This is useful if promise2 depends on something from promise1.
Also, You code should be promise1.then(returnsSomePromise2).then(...); it wants a function in .then() where before it was getting a promise (promise2). The function it calls will return the promise and it will chain it.
Option 3 will fire them in parallel and resolve a function when both (all) have been completed. $q.all() can take an array OR an object. In the case o an array, which you have in your example. The function passed to .then() will be passed an array. The array lines of with the order of the promises passed to $.all().
$q.all([promise1, promise2]).then(function(result){
var promise1Result = result[0];
var promise2Result = result[1];
})
If you pass an object, with named keys, you will get an object back in the function passes to .then(). The keys will line up with the object passed to $q.all()
$q.all({myFirstPromise:promise1, secondPromise:promise2}).then(function(result){
var promise1Result = result.myFirstPromise;
var promise2Result = result.secondPromise;
})

AngularJS $http use data into controller

I'm new in AngularJS so if the question is not 'intelligent' for you, please don't rate it in negative. If someone ask a question, for he isn't stupid.
So..
I would like to use data from an ajax request, like this:
encryptApp.factory('getData', function($http, $rootScope) {
var getData = {};
getData.tot_of = function() {
return $http.get('/path/to').then(function(result) {
return result.data;
});
}
getData.get_info = function() {
return $http.get('/path/to').then(function(result) {
return result.data;
});
}
return getData;
});
In controller I use this:
getData.get_info().then(function(get_info) {
$scope.get_info = get_info;
});
// HERE THE $scope.get_info is UNDEFINED
I'm new in AngularJS and I don't know why does this. So, is there a method that I can use the json data outside the " then function ".
Thanks and please don't rate this question negative. Sorry if my english is not good.
$http.get returns a promise.
By essence, a promise is as Javascript saying:
"Hey ! I let you make the request, but please, I don't want to wait for you, so when you finished, please execute the callback I'm just passing you, since now, I will forget you since I have more code to execute while you're doing your job".
In other words, a promise's callback isn't executed immediately, since the goal is to not block the Javascript "thread" (Javascript is like single-threaded).
So your current code is acting like this:
getData.get_info().then(function(get_info) { //the function inside this "then" IS the callback
$scope.get_info = get_info;
});
// Hey !! The request might not finish ! So don't expect $scope to have the value you expect here !
So the simple example to illustrate would be to imagine that your ajax request takes 100ms to execute.
Within those 100ms, your next Javascript scope is very very very likely to be already reached, having $scope.get_info not initialized yet.
Without promise, your next code, outside of the callback, that should not depend of $scope.get_info, would have to wait 100ms to start, wasting time.
So, is there a method that I can use the json data outside the " then
function ".
There is a way, using broadcasting/emit ($rootScope.$broadcast/$rootScope.$emit) to trigger a corresponding event, but it's often more "anti-KISS" for a simple case.
I advise you to put all your depending code in the promise callback.
To clean your code, merely call a private function that you define outside the callback.

Resources