pro.mean pro.mean - 1 year ago 57
AngularJS Question

what is the usage of $q and promise when we need callback for several metods

I am using angularJS and trying to creating amazon VPC through aws.sdk.js

Now when I create VPC I have to done various configuration and call below methods in chain

  1. create vpc
    () => vpc_

  2. create internet gateway
    () => igw_

  3. attach internet gateway
    (vpc_, igw_) =>

  4. create subnet
    (vpc_) => subnet_

  5. create route table
    (vpc_) => rtb_

  6. associate route table
    (rtb_, subnet_) =>

  7. create security group
    (vpc_) => sg_

  8. add inbound rule
    (sg_) =>

  9. additionally create tags for each generated resources .

as you can see some function parameter depends on previous function and so on. I am using $q services on each AWS method but this is became so large callback hell.

I also capture notifications of each function in back so my input function became like this

functionOne().then(function(res1) {;
functionTwo( {;
......... series of functions within function....
.then(res7) { functionEight( {
}, function (err) {}, function (notify) {})
.finally(function(){ console.log('Finally done everything'); });
}, function (err2) {
}, function (notify2) {
}, function (err1) {
}, function (notify1) {

my function signature is as below

functionX: function() {
var d = $q.defer();
var params = {
ec2.anyMethodName(params, function(err, data) {
if (err) {
} else {
d.notify('Notifications methods');
return d.promise;

You can see the chaining of methods in my controller here

So my question is

  • Does Amazon native thenable promise property can be used in angular? if yes then how do we implement notifications?

  • Is there any sorter way to do that? like error will be captures in last? using
    but do not not how?

  • If i use
    on functionOne than it throw error in console
    .finally is not a function

Answer Source

Why don't you

    .then(functionTwo) // calls functionTwo(responseOne)
    .then(functionThree) // calls functionThree(responseTwo)

Edit: If you want to access the result of functionOne in functionThree, you can do the following:

functionTwo(resultOne) {
    var promise = d.promise;
    promise.then(function(resultTwo) {
       return [resultOne, resultTwo];
  return d.promise

Refer to this answer for more details.

You don't need to necessarily have to write anonymous callbacks as promise resolve and reject handlers

Your callbacks will be called with the resolved/rejected promise from the previous function automatically.

If you want your entire chain to fail if any one promise fails, you call always use .all(), so that's something you should pay attention to if you want to use .all().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download