2

I am working on an application that heavily depends on asynchronous data operations. I am dealing with those through promises.

However, while my code works, I have the feel that it is getting chaotic and hard to maintain in the future.

Assume this:

validate().then(

// success
function(promise){
    $http.post('stuff.php',data).then(

      function(p){

      },
      function(){

      }
    ) 
},

// failure
function(reason){
    // Assume another promise-depending operation
},

// notification
function(update){

}
);

As you can see, promise calls are heavily nested. Furthermore, I have to deal with resolve/reject methods in each and every step.

What am I missing; how can I improve my technique?

1 Answer 1

3

You seem to be using promises the same way someone would use callbacks. While you can do that it doesn't really make sense, callbacks can do that too.

Main feature of promises is that resolvers/handlers can return value and it allows a chaining, consider following example:

  function capitalise (word) {
    letters = word.split('');
    letters[0] = letters[0].toUpperCase();
    return letters.join('');
  }  

  function exclamate (word) {
    return word + '!'   
  }

  function log (word) {
    console.log("Word is:", word);
    return word
  }

  // Let's say that getWord is asynchronous operation (say ajax)
  // that returns a promise.
  word = getWord("i want coffee");
  word.then(capitalise).then(exclamate).then(log);
2
  • Thank you. What would getWord() return? Also, how would i catch an error? Commented Jan 6, 2014 at 14:02
  • 1
    getWord returns promise, it's equivalent of getWord(…).then(…) Catching errors depends on a framework or library you are using, usually there is a catch method on Promise. Commented Jan 6, 2014 at 14:20

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.