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?

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);
  • Thank you. What would getWord() return? Also, how would i catch an error? – Sprottenwels Jan 6 '14 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. – David Sergey Jan 6 '14 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.