It's all about the answers!

Ask a question

DNG - Javascript - Adding values which are returned one at a time from an asynchronous function


Sean F (1.3k252162) | asked Aug 17 '18, 2:40 p.m.


The following code is accessing the RM API

'row' is an object with links to 2 other objects

The code follows the links to grab the objects at the other end of each link and retrieve the integer attribute value 'Cost' from each linked object. It then sums the values and writes the result into the Total attribute of the original object.

The problem is that it is not behaving reliably. Sometimes it assigns the sum correctly but sometimes it assigns only the value of one of the linked objects instead of the sum of both.

I do the assignment twice inside the innermost nested callback function instead of once after the link loop since I don't know how to do the assignment  outside the callback due to the asynchronicity of javascript - but I thought it would still work even though I am probably not doing it the way it should be done.

The unpredictability of the result suggests it is an asynchronicity issue.

    function getLinks(row)
    {    
        RM.Data.getLinkedArtifacts(row, [], function(linksResult)
        {
            var linkedArtifactsTotal = 0;

            linksResult.data.artifactLinks.forEach(function(linkDefinition)
            {
                linkDefinition.targets.forEach(function(target)
                {
                    getAttrVal(target, "Cost", function(result)
                    {
                        linkedArtifactsTotal = linkedArtifactsTotal + result;
                        varStrResult = linkedArtifactsTotal + "";
                        setAttrVal(row, "Total", varStrResult)
                    });
                });
            });

        });
    }

    function getAttrVal(ref, attrName, callback)
    {    
        RM.Data.getAttributes(ref, attrName, function(result)
        {
            var attributes = result.data;
            
            attributes.forEach(function(attr)
            {
                var attrVal = attr.values[attrName];
                callback(attrVal);
            });
        });
    }

    function setAttrVal(ref, attrName, newValue)
    {    
        // function that sets an attribute value
    }



Be the first one to answer this question!


Register or to post your answer.


Dashboards and work items are no longer publicly available, so some links may be invalid. We now provide similar information through other means. Learn more here.