1

I am running the following code. Where I am expecting to see the outputs latitude and longitude, what I get is Promise{<pending>} in my console. Why is this the case? I thought using async/await helps to eliminate the problem of pending promises since the code can't go forward until the promise fulfills. How do I solve this problem?

const issURL = 'someUrl';
async function getData() {
            const res = await fetch(issURL);
            const data = await res.json();
            const {
                latitude,
                longitude
            } = data;
            return (latitude, longitude);
        }
console.log(getData());
vinshield
  • 17
  • 6
  • 2
    You need to `await` your call to `getData()` as well – Elan Hamburger Jun 18 '22 at 19:59
  • Or `.then(res => console.log(res))`. If you're trying to make the function return a value synchronously, that's not possible\*. – ggorlen Jun 18 '22 at 20:04
  • Calls to async functions will return the result wrapped in a promise, so you'll have to `await` your call to `getData()` to get the result. – Oskar Grosser Jun 18 '22 at 20:25
  • 2
    Note that the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) in JavaScript will evaluate all comma-separated statements, but only return the result of the final statement. Therefore you only return `longitude` in `getData()`. Did you mean to return an object created in [object literal notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_notation_vs_json)? – Oskar Grosser Jun 18 '22 at 20:27
  • @ElanHamburger okay, that means I can only get what I want by calling getData() within another async function? – vinshield Jun 18 '22 at 21:31
  • @OskarGrosser you were right. So how can I return an object like you said? – vinshield Jun 18 '22 at 21:32
  • Use `{}` instead of `()` – ggorlen Jun 18 '22 at 21:36

1 Answers1

0

Since the getData() function needs some time to resolve its promise, you have to await it as well. Alternatively, you can use getData().then((res) => console.log(res))