How to take an javascript object out of a database query to access in the rest of the script

74 Views Asked by At

To be able to push markers to the map i need to have the returned data outside of the querying function, but I cant get the data out or return it from the query, how can i make it a global variable, or how can I return the object so I can access it in the rest of the script (not just in the success: function), any help would be appreciated

        var query = new Parse.Query("business_and_reviews");
        var results = new Parse.Object("business_and_reviews");

        query.get("pLaARFh2gD", {
            success: function(results) {
                console.log(results["attributes"]["lat"]);
                lat = results["attributes"]["lat"];
                lng = results["attributes"]["lng"];
                myLatLng2 = (lat + "," + lng);
                console.log(myLatLng2);
                myLatLng = new google.maps.LatLng(myLatLng2);
                },
            error: function(object, error) {
            }
        });
        //lat = results.get(["attributes"]["lat"]);
        console.log(lat);
    }
1

There are 1 best solutions below

1
On

You can create a global object (if you really want) and reference it directly in the success object.

However, I'd personally use callbacks to handle the data for both success and fail.

You'd end up with something along the lines of:

//success callback
function createMap(data){
    var latlong = data["attributes"]["lat"] + ',' + data["attributes"]["lng"]
    var map = new google.maps.LatLng(latlong);
}

//fail callback
function failure(reason){
    console.log(reason)
}

//initialising function used to call the API
function initMap(){
    getLatLong(createMap, failure)
}

//handles api with callbacks supplied
function getLatLong(successCallback, failCallback){
       var query = new Parse.Query("business_and_reviews");
        var results = new Parse.Object("business_and_reviews");

        query.get("pLaARFh2gD", {
            success: function(results) {
                    if(typeof successCallback ==='function') {
                        successCallback(results)
                    }
                },
            error: function(object, error) {
                if(typeof successCallback ==='function') {
                    failCallback(error)
                }
            }
        });
}
//call the function
initMap();