0
const request = require('postman-request');


const geocode = (address) => {
  const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${address}.json?access_token=pk.eyJ1IjoibWVya3VyMTIzIiwiYSI6ImNrYjVndDk3bjBvNGEyeW16cHlid2txZ3YifQ.NGOWOq0yq0wvkhzDzjnUpQ&limit=1`;
  request({ url, json: true }, (error, response) => {
    const data = response.body;
    if (error) {
      return 1;
    } else if (data.message === 'Not Found' || data.features.length === 0) {
      return 1;
    } else {
      return {
        longitude: data.features[0].center[0],
        latitude: data.features[0].center[1],
        location: data.features[0].place_name,
      };
    }
  });
};

output = geocode("New York");

console.log(typeof output);

Hi guys, I know that the code doesn't work and that I should use a callback function but I was wondering why that's actually the case. Why can't I return the result, which in this case is an object, and access it as normally?

Thanks for every helpful response!

CNNTT
  • 27
  • 1
  • 7
  • 2
    Because API calls are asynchronous. – Barmar Jun 08 '20 at 22:25
  • You are already using a callback, which is why that `return` doesn't work. It's not inside your `geocode` function, it's inside the anonymous callback function you're passing to your `request()` call as 2nd argument. Your `geocode` function doesn't return anything. However to save people from the so-called callback hell, JS supports async and await, which *does* kind of allow you to write the code you want to write. –  Jun 08 '20 at 22:34
  • Yes, but I only call return when the API is finished, so Why? – CNNTT Jun 08 '20 at 22:37
  • It doesn't matter *when* you call return, it matters *where* you're calling it. Again: *your `geocode` function doesn't return anything*. The request is asynchronous and will finish at an arbitrary point in the future, but node just keeps executing your commands, that's why you need a callback in the first place: to tell node what it is supposed to do a few seconds from now, when the API call has finished. But anything you return from the callback is discarded because you are not calling the callback function yourself and therefore cannot assign it to anything. –  Jun 08 '20 at 22:41
  • Here's the code rewritten to use async/await: https://jsfiddle.net/khrismuc/Lbp0hd25/ –  Jun 08 '20 at 22:43
  • Thanks a lot for your help, I actually did it with a callback function originally but Then this question came into my mind! – CNNTT Jun 08 '20 at 22:46
  • You're welcome :) –  Jun 08 '20 at 22:47

0 Answers0