How can I obtain API response data from within a function?

get data from api javascript
get data from server javascript
javascript get data from url
fetch api
fetch api example
fetch get params
return data from fetch
javascript fetch json from url

Javascript noob here. Apologies if there are a ton of duplicate questions out there because it seems like this must be a fundamental js function thing, but I honestly can't find an answer to this. I'm trying to wrap an API GET call in a function, and I'm running into behavior that I don't understand. The code in question:

I'm using the node-rest-client package to call the mapquest geocoding API. I'm interested in the lat/long data only. var Client = require('node-rest-client').Client;

If I make the GET call like this, I can access parsed as an object, which is what I want.

var address = 'New York'
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
                'key=' + mapquestKeys.consumer_key +
                '&location=' + address,
            function(data, response) {
              parsed = data.results[0].locations[0].latLng
              }
            );

// parsed == {lat, long}

But if I wrap this in a function:

function geocode(address){
  var client = new Client();
  var parsed;
  client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
                  'key=' + mapquestKeys.consumer_key +
                  '&location=' + address,
              function(data, response) {
                parsed = data.results[0].locations[0].latLng
                }
              );
    return parsed
}

var address = 'New York'
parsed = geocode(address);

// parsed === undefined

parsed doesn't seem to be affected by the inner function; it's undefined. How can I return parsed as an object containing the data I want as in the first example? What the heck is going on here?


In:

function geocode(address){
  var client = new Client();
  var parsed;
  client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
                  'key=' + mapquestKeys.consumer_key +
                  '&location=' + address,
              function(data, response) {
                parsed = data.results[0].locations[0].latLng
                }
              );
    return parsed
}

var address = 'New York'
parsed = geocode(address);

// parsed === undefined

You never defined parsed outside of the scope of your function. Also you're returning parsed inside of the function before it's had a chance to retrieve from the GET request. If you wanted to do it this way, you'd need to put return(prased) inside the callback function of client.get. A better way to do it is to wrap it inside a Promise like so:

function geocode(address){
    return new Promise((resolve, reject) => {
        var client = new Client();
        client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
                'key=' + mapquestKeys.consumer_key +
                '&location=' + address,
                function(data, response) {
                if(data){
                    resolve(data.results[0].locations[0].latLng)
                }
                else{
                    reject(response)
                }
                  });
    })
  };


var address = 'New York';
var parsed;
geocode(address).then(function(latlong){
    parsed = latlong
}).catch(err => {
    console.log(err)});

Here, parsed will only evaluate to latlong once the Promise has been resolved (the GET request has returned successful). It will also reject the Promise if data of the GET request is NULL and return an error.

If you wanted to then do something with parsed you could include that in the .then() statement.

Learning how to code in Javascript means learning how to write code asynchronously. Promises help you treat things which are by default asynchronous as synchronous.

Help needed on passing the response data to another function , api.js exports.getdata = (data) => { fetch(url) .then(function(response) { return will always return undefined , no matter what happens within it. but note that this is not a place to ask usage questions whenever you get stuck! Returning data from Axios API. I am trying to use a Node.JS application to make and receive API requests. It does a get request to another server using Axios with data it receives from an API call it receives. The second snippet is when the script returns the data from the call in.


You never defined parsed in scope (externally to the function):

function geocode(address){
  var client = new Client();
  var parsed;
  client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
                  'key=' + mapquestKeys.consumer_key +
                  '&location=' + address,
              function(data, response) {
                parsed = data.results[0].locations[0].latLng
                }
              );
    return parsed
}

var address = 'New York'
var parsed = geocode(address);

Notice the var parsed = geocode(address);

Fetching data from the server, This is achieved by using APIs like XMLHttpRequest or — more recently — the We'll just use the GET method here and set the URL as our url variable. When this has occurred, the response data will be available in the  Define response and request relative to data API data access. Define API endpoint in the context of the SODA API. Be able to list the 2 potential responses that you may get when querying a RESTful API. Use the mutate_at() function with dplyr pipes to adjust the format / data type of multiple columns.


you need to wrap this into a promise, or return the result with callback. Callback would be like this:

function call(arg, callback) {
 client.get("http:////" + arg, function (data, response) { 
  callback(data.results[0].locations[0].latLng)
 });
}

call("yolo", function (parsed) { console.log(parsed) })

promise is well described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

How to Use the JavaScript Fetch API to Get Data ― Scotch.io, redirect() - This method creates a new response but with a different URL. arrayBuffer() - In here we return a promise that resolves with an  There are many different types of requests. The most commonly used one, a GET request, is used to retrieve data. We can use a simple GET request to retrieve information from the OpenNotify API. OpenNotify has several API endpoints. An endpoint is a server route that is used to retrieve different data from the API.


Get Started With Node: An Introduction To APIs, HTTP And ES6+ , Alternatively, a callback function might take in an error object and a response object as arguments, and present them when the async function  Getting response headers data from an AJAX request with javascript Posted on 9 January, 2016 by Felipe Lavín Z. Response headers can contain valuable information and may help to keep your API responses simpler by separating the actual response data from accessory metadata.


Getting HTML with fetch() in vanilla JS, the response we get back from fetch() is a ReadableStream. With a typical API request, we use the json() method to get a JSON object from  Background on APIs API is short for Application Programming Interface. Basically, it means a way of accessing the functionality of a program from inside another program. So instead of performing an action using an interface that was made for humans, a point and click GUI for instance, an API allows a program to perform that action automatically.


How to use the Fetch API with vanilla JS, To get our API data as a JSON object, we can use a method native to then work with the actual response JSON in a chained then() method. The idea is to get all the data from the Random User API and display it in list items inside the author's list. Essential Reading: Learn React from Scratch! (2020 Edition) The first step is to actually set the URL we need and also the list we are gonna put the data in, so in the Javascript we write: const ul = document.getElementById('authors