Pavel Evdokimov Pavel Evdokimov - 2 months ago 8
AngularJS Question

Multiple steps to process data, what's good pattern for JS/Angular?

Imagine we have few steps to process data. First we download it, then we do smth else and so on many times. Code in C# it would look like several lines - one for each step.

As I understand now, in JS/Angular it would look like this:



function prepateAndGo() {

loadData()
.$promise.then((loadedData) => {

prepareData(loadedData).$promise().then((preparedData) => {

preprocessData(preparedData).$promise().then((preprocessedData) => {

andDoSmthElse(preprocessedData).$promise().then((andDoSmthElseData) => {

makeupData(andDoSmthElseData).$promise().then((makeupedData) => {

Console.log('finally, everything is loaded and processed, lets go');

});
});
});
});
});
}





Isn't there more beautiful pattern? What's common solution against spaghetti?

Answer

What you need to do is create utility functions that return a promise. For example:

function prepareData(data){
    // do something with data and return a promise
    return $q.when(data);        
}

Then you can chain the promises nicely. For example:

loadData()
    .then(prepareData)
    .then(preprocessData)
    .then(andDoSmthElse)
    .then(makeupData)
    .then(function(madeData){
        Console.log('finally, everything is loaded and processed, lets go');
    });

Note: Code is off the top of my head, but should get you started

Comments