Jazz Forum Welcome to the Jazz Community Forum Connect and collaborate with IBM Engineering experts and users

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


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
    }



0 votes


Be the first one to answer this question!

Register or log in 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.

Search context
Follow this question

By Email: 

Once you sign in you will be able to subscribe for any updates here.

By RSS:

Answers
Answers and Comments
Question details
× 10,941

Question asked: Aug 17 '18, 2:40 p.m.

Question was seen: 1,215 times

Last updated: Aug 17 '18, 2:40 p.m.

Related questions
Confirmation Cancel Confirm