Skip to content Skip to sidebar Skip to footer

A Bit Confused With Promises/chained Functions In Javascript

I'm still trying to get my head around all this and I'm obviously missing some fundamental concepts. In my code I have a scenario whereby I want to call several functions in a row

Solution 1:

I understand that this is obviously something to do with my functions, but I don't really understand what I need to do differently

You need to return promises from them. Your current genericCalc function does not even contain a return statement (only the forEach callback function inside it does), so it does return undefined.

If you need to wait for the result of each article, use Q.all like you have already done with fnArray (which is a promiseArray actually). In genericCalc it should look like this:

var genericCalc = function (calcPrefix) {
    return Q.all(prjArticleArray.map(function (thisArticle) {
        var calcPromise = calcEOL(res_Array, thisArticle);  //another function containing async ajax call
        var result = calcPromise
                .then(calcsDone)
                .fail(calcsFailed);
        return result;
        …
    });
};
var res_Array = ko.observable(); //holds returned results//do calculation subtotals here and set a knockout observable value

That is a bad idea. You should not use global variables that are set somewhen and use promises just for propagating changes, but the promises should represent these values. This leads to a better, functional programming style.

So instead of setting a global variable, do return the result from your calcsDone function, and it will resolve the result promise with that value.


Post a Comment for "A Bit Confused With Promises/chained Functions In Javascript"