1
votes

I have a function foo that calls another function moreFoo and I want to wrap the function calls in promises so that the promise returned by foo returns after moreFoo has resolved. Here is my solution:

function foo() {
  var defer = $q.defer();
  console.log('doing foo');
  moreFoo().then(defer.resolve);
  return defer.promise;
}

function moreFoo() {
  var defer = $q.defer();
  setTimeout(function() {
    console.log('doing more foo');
    defer.resolve();
  }, 2000);
  return defer.promise;
}

foo().then(function() {
  console.log('finished with all foos');
});

This then outputs:

doing foo
doing more foo
finished with all foos

It appears to be working as intended. Is this the correct/best way to chain these promises?

3
What is your criteria for "correct/best?" - Robert Harvey

3 Answers

2
votes

I don't know about "best", but this can be simplified a lot by leveraging $timeout the promise it returns...

function foo() {
  console.log('doing foo');
  return moreFoo();
}

function moreFoo() {
  return $timeout(function() {
    console.log('doing more foo');
  }, 2000);
}

foo().then(function() {
  console.log('finished with all foos');
});
0
votes

I like this way ( $timeout returns promise):

 function foo() {
      return $timeout(function(){
           console.log('doing foo');
       },2000);
 }

 function moreFoo() {
      return $timeout(function(){
           console.log('doing more foo');
       },2000);
 }        

 foo()
     .then(moreFoo)
     .then(function(){ 
          console.log('all foos done');
      }, function() {
         console.log('something went wrong');
      });

This example shows two promises chained together. The second executes only after the first one succeeds. If either fails, the last error handler is called.

0
votes

Can run both simultaneously and not even need to chain them by using $q.all()

$q.all([ foo(), moreFoo()]).then(function(data){
    console.log(data) /* array of responses from all resolved promises */
});

Good reference: https://egghead.io/lessons/angularjs-q-all