Search code examples
javascriptangularjspromisechainingangular-promise

AngularJS : Is this the correct way to chain promises?


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?


Solution

  • 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');
    });