0

I am using javascript to access the API of a database and this is one of my functions

function getAttrVal(ref, attrName)
{   
    var result = "null"

    RM.Data.getAttributes(ref, attrName, function(result)
    {
        var attributes = result.data;

        attributes.forEach(function(attr)
        {
            var attrVal = attr.values[attrName];
            println("Check " + attrVal)   // here it is printing 'Check 5' which is correct since attrVal should equal '5'
            result = attrVal;
        });
    });

    return result;   // but here it returns the value 'null'
}

How do I get the variable 'result' to be 5 when it is returned.

It seems to be a variable scope issue.

TIA

Yes I am a dumb noob with javascript!

1 Answers1

0

tldr; You're right it's a variable scoping issue.

You have 2 variables defined as result, one within the scope of your forEach iteration and one in the parent scope. Try renaming the iteration variable:

function getAttrVal(ref, attrName){   
    var result = "null";

    RM.Data.getAttributes(ref, attrName, function(_result)
    {
        var attributes = _result.data;

        attributes.forEach(function(attr)
        {
            var attrVal = attr.values[attrName];
            println("Check " + attrVal)   // here it is printing 'Check 5' which is correct since attrVal should equal '5'
            result = attrVal;
        });
    });

    return result;   // but here it returns the value 'null'
}