diff --git a/node_helper.js b/node_helper.js index b9c0e5c..cb7c61d 100644 --- a/node_helper.js +++ b/node_helper.js @@ -6,7 +6,7 @@ */ var NodeHelper = require("node_helper"); -var request = require('request'); +var fetch = require('node-fetch'); var moment = require('moment'); module.exports = NodeHelper.create({ @@ -21,36 +21,35 @@ module.exports = NodeHelper.create({ if (notification === 'GOOGLE_TRAFFIC_GET') { //first data opull after new config - this.getPredictions(payload); - - } + (async () => {await this.getPredictions(payload);})(); + } }, - - - getPredictions: function(payload) { - var self = this; + + getPredictions: async function(payload) { var returned = 0; var predictions = new Array(); - - payload.destinations.forEach(function(dest, index) { - request({url: dest.url, method: 'GET'}, function(error, response, body) { +// console.log("MM-MyCommute-DEBUG PAYLOAD GET PREDECTIONS: "+ JSON.stringify(payload,undefined,2)); + + for (let index = 0 ; index < payload.destinations.length ; index++) { + var dest = payload.destinations[index] ; + try { + var body = await fetch(dest.url); + var data = await body.json() ; + await new Promise(resolve => setTimeout(resolve, 200)); // wait 200ms to prevent overlading the interface. + +// console.log("MM-MyCommute-DEBUG ("+ index + "): "+ JSON.stringify(data,undefined,2)); - var prediction = new Object({ - config: dest.config - }); - - if(!error && response.statusCode == 200){ - - var data = JSON.parse(body); + var prediction = new Object({ + config: dest.config + }); - - if (data.error_message) { + if (data.error_message) { console.log("MMM-MyCommute: " + data.error_message); prediction.error = true; - } else { - + } else { + var routeList = new Array(); for (var i = 0; i < data.routes.length; i++) { var r = data.routes[i]; @@ -86,21 +85,17 @@ module.exports = NodeHelper.create({ } - } else { - console.log( "Error getting traffic prediction: " + response.statusCode ); + } catch(error) { + console.log( "Error getting traffic prediction: " + error ); prediction.error = true; - } - - predictions[index] = prediction; - returned++; - - if (returned == payload.destinations.length) { - self.sendSocketNotification('GOOGLE_TRAFFIC_RESPONSE' + payload.instanceId, predictions); }; + predictions[index] = prediction; + }; + + this.sendSocketNotification('GOOGLE_TRAFFIC_RESPONSE' + payload.instanceId, predictions); - }); - }); - } - + } + + }); \ No newline at end of file diff --git a/package.json b/package.json index c7943fc..b6181af 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,6 @@ "homepage": "https://github.com/jclarke0000/MMM-MyCommute#readme", "dependencies": { "moment": "^2.18.1", - "moment-duration-format": "^1.3.0", - "request": "^2.81.0" + "moment-duration-format": "^1.3.0" } }