Search code examples
javascriptasynchronousfieldresponsefetch

Add a new field to Javascript Fetch response object


I am doing a map with markers. I got the geo coordinates data from fetching a google api url. But for the markers, I need additional information coming from elsewhere. Is it possible to attach this additional information to the response I got from fetching the url? Thanks a lot!
The code:

var location = "Seattle";
var username = "Test user";
var time = "8th March 2017";

function toMap(location, username, time) {
    if (location.length > 0) { 
        var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&key=Your_API_Key";
        fetch(googleURL)
            .then(function(response) {

     // Can I add "location", "username", and "time" to the response result here 
     //  before returning it?????

                return response.json();
             })
            .then(addMarker);
    }
}

Solution

  • Because response.json() returns a Promise of Object, you can do it in another then() callback.

    var location = "Seattle";
    var username = "Test user";
    var time = "8th March 2017";
    
    function toMap(location, username, time) {
        if (location.length > 0) { 
            var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&key=Your_API_Key";
            fetch(googleURL)
                .then(function(response) {
                    return response.json();
                })
                .then(function(json) {
                    json.location = location;
                    json.username = username;
                    json.time = time;
                    return json;
                })
                .then(addMarker);
        }
    }