1

I'm trying to load 3 characters from 5 difference websites and a concatenate them into one string, even though I'm using a try & catch statement the strings say'uncaught reference error' and any codes with numbers cause a 'unexpected tokens error'. I'm using the P5.js framework at the moment but willing to try plain .js.

Thanks

My code:

var data;
function setup(){

    var url = [];

    url[0] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'
    url[1] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'
    url[2] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'
    url[3] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'
    url[4] = 'https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=NRpxYLm9hCkAkhy0OSjEPA%3D%3D.json'

    try{
        for (let i = 0; i < 5; i++){
            data += loadJSON(url[i], gotData, 'jsonp') + ' '
        }
    } catch (data){
        console.log('oh well');
    }

}

function draw(){
    createCanvas(400,400);
    background(225);
    text(data, 0, 200);
}

function gotData(data){
    text(data, 100, 200);
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • 1
    Can you add the actual error printout? – Mikko Dec 14 '17 at 22:24
  • `gotData, 'jsonp'` ... they should be the other way around, shouldn't they? `loadJSON(path,[jsonpOptions],[datatype],[callback],[errorCallback])` `dataType` appears before `callback` in that function syntax – Jaromanda X Dec 14 '17 at 22:38
  • Have you tried initializing your variable using `var data = "";`? – techfly Dec 14 '17 at 22:40

1 Answers1

0

From the P5.js reference:

Loads a JSON file from a file or a URL, and returns an Object. Note that even if the JSON file contains an Array, an Object will be returned with index numbers as keys.

This method is asynchronous, meaning it may not finish before the next line in your sketch is executed.

That last line explains what's going on: the loadJSON() function is asynchronous, which means it doesn't directly return anything. So lines like this don't make sense:

data += loadJSON(url[i], gotData, 'jsonp') + ' '

Please see the examples in the reference to understand how to use the loadJSON() function correctly, but basically you either need to use a callback function or you need to use the preload() function.

Community
  • 1
  • 1
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107