https .get(apiUrl, dataRecr.getReadDataFct()) .on("error", errorCallback);
class DataReceiver { constructor(finishFct) { this.apiResult = null; this.dataString = ''; this.finishFct = finishFct; }
receiveNextChunk(chunk) { //console.log('chunk: ' + chunk); this.dataString += chunk; }
finishReceivingData() { //console.log('dataString: ' + this.dataString); try { this.apiResult = JSON.parse(this.dataString); this.finishFct(this.apiResult); } catch(exception) { console.log(`Error calling API: ${this.dataString}`); throw exception; } }
static showApiResult(results) { //result is array of pairs {unit, value} //if not array, assume we have error if (!Array.isArray(results)) log(results.toString()); else results.forEach(pair => log(`${pair.value} ${pair.unit}`)); }
-- API Data Received -- 2 m 6.56168 ft 2000 mm 200 cm 0.002 km 78.74016 in 0.00124 mi 2.18723 yd