javascripthtmltin-can-api

This is inefficient, how can I loop instead?


I'm trying to pull down two verbs and their associated statements and this code works but I recognize that it is inefficient. I tried putting the verbs in an array then referencing the array item in each line where the verb is named but that threw an error. What code can I use to make this loop through a verbs array that I build? Thank you.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Get 2 verbs</title>
        <script src="xapiwrapper.min.js"></script>
    </head>
    <body>
        <div id='demo'></div>
        <script>

                var text = "";
                ADL.XAPIWrapper.changeConfig({"endpoint":"https://lrs.adlnet.gov/xapi/"});            
                var search = ADL.XAPIWrapper.searchParams();
                search['verb'] = ADL.verbs.completed.id;
                search['since'] = "2017-08-08T08:34:16Z";
                var res = ADL.XAPIWrapper.getStatements(search);
                if (res) {
                    text = JSON.stringify(res);
                    }              

                var text2 = "";
                ADL.XAPIWrapper.changeConfig({"endpoint":"https://lrs.adlnet.gov/xapi/"});            
                var search = ADL.XAPIWrapper.searchParams();
                search['verb'] = ADL.verbs.resumed.id;
                search['since'] = "2017-08-08T08:34:16Z";
                var res = ADL.XAPIWrapper.getStatements(search);
                if (res) {
                    text2 = JSON.stringify(res);
                    }   

            document.getElementById('demo').innerHTML = text + text2;
        </script>
    </body>
</html>

Solution

  • Maybe something like this instead? Untested of course.

    var configs = [
      {
        endpoint: 'https://lrs.adlnet.gov/xapi/',
        verb: ADL.verbs.completed.id,
        since: "2017-08-08T08:34:16Z"
      },
      {
        endpoint: 'https://lrs.adlnet.gov/xapi/',
        verb: ADL.verbs.resumed.id,
        since: "2017-08-08T08:34:16Z"
      }
    ];
    
    var out = '';
    configs.forEach(function(cfg) {
      ADL.XAPIWrapper.changeConfig({"endpoint":cfg.endpoint});
      var search = ADL.XAPIWrapper.searchParams();
          search['verb'] = cfg.verb;
          search['since'] = cfg.since;
      var res = ADL.XAPIWrapper.getStatements(search);
      if (res) {
        out += JSON.stringify(res);
      }
    });
    
    console.log(out);