Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am working on an application that heavily depends on asynchronous data operati

ID: 647135 • Letter: I

Question

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?

Explanation / Answer

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);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote