Friday 19 May 2017

Api data with async of Node.js and retrieving data make it sync

Im needing help with a Node weather app I'm making. Im using Google API to get me the longitude and latitude of an address and feed this into the Dark Sky API to return the weather in a JSON format.

My issue is the that most of the time the weather API does the search before the google API has returned the longitude and latitude. I know why its doing it because of the async nature of Node. My question is how do i make this part sync instead?

var express = require('express');
var https = require('https')
var bodyParser = require("body-parser");

var app = express();

app.use(bodyParser.urlencoded({
extended: true
}));

app.use(bodyParser.json());

var lon;

var lat;

app.post('/', function(req,res,next){

var search = req.body.search;


function google(){

    var api = "AIzaSyCaVdDyt2Pj0kXt9lrbJIBrhKbLO4b5P9Y";

    var url = https.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${search}&key=${api}`, function(res3){

        var body = "";
        var googleResults;

        res3.on('data', function(data){
            body += data.toString();
        })

        res3.on('end', function(){

            googleResults = JSON.parse(body);
            //console.log(body);
            lat = googleResults.results[0].geometry.location.lat;
            lon = googleResults.results[0].geometry.location.lon;
            console.log(search);
        })

    });

}


google();

//connectc to API URL()
var request = https.get(`https://api.darksky.net/forecast/7c41453dc9e5976eecb6a38487427b58/${lon},${lat}`, function(res2){

console.log(lon + " " + lat)
            var body = "";
            var weather;
            //Read the data
            res2.on('data', function(data){
                body += data.toString();

            })

            res2.on('end', function(){
                    //Parse the data
                     weather = JSON.parse(body);
                    //Print data
                    //console.log("test = " + weather.currently.temperature)
                    res.render('index', {
                        temperature: weather.currently.temperature,
                        humidity: weather.currently.humidity,
                        wind: weather.currently.windSpeed
                    });
            })

});



});



via monkeyman905

No comments:

Post a Comment