-1

I am having trouble resolving this promise.

const getAge = (actorId) => {
    return (
        axios.get(`https://api.themoviedb.org/3/person/${actorId}?api_key=${process.env.REACT_APP_API_KEY}&language=en-US`)
            .then(function (response) {
              return moment().diff(response.data.birthday, 'years')
            })
            .catch(function (error) {
              console.log(error);
            })
        )
    }

console.log(getAge('5000'), 'FUNCTION')

It doesnt ever resolve the promise and returns pending

enter image description here

I have tried a number of different ideas and none seem to work. What Am I missing?

Thanks

JDB
  • 25,172
  • 5
  • 72
  • 123
Jkaram
  • 611
  • 2
  • 7
  • 13
  • 3
    That's what's supposed to happen. An async function always returns a promise. You can't use it to magically synchronise an asynchronous process. – jonrsharpe Mar 09 '20 at 18:17
  • I don't see any attempt to resolve in the code you have posted. Can you add that code? Common approaches include call backs, composition and async/await, but you can never return from a concurrent function. Hard to say what approach is the best without knowing what you are trying to do – sinanspd Mar 09 '20 at 18:19
  • add a then to getAge(5000) and you should be fine – EugenSunic Mar 09 '20 at 18:19

1 Answers1

7

You need to call .then to get the value or wrap the call within a async function. For example:

getAge('5000')
  .then(val => console.log(val, 'FUNCTION'));

Alternatively, wrapping with async:

(async () => {
  const val = await getAge('5000');
  console.log(val, 'FUNCTION');
})();
stackunderflow
  • 1,644
  • 6
  • 24
  • 40