1

I want to assign the value returned from an async function to a variable, but I am getting a promise instead of a value even do I am awaiting for the promise in the async function.

    import axios from "axios";

    async validateName(userName) {
       const url = "abc/xyz";
       try {
         const response = await axios.get(url);
         return response;
       } catch(err) {
           return false;
       }
    }

    const validate = validateName(userName);
    console.log("validate:", validate); // outputs Promise {<pending>}, but I am expecting the actual value which is true or false;

Please suggest any change I need to make as I am new to async await.

tsinat
  • 235
  • 1
  • 3
  • 16
  • 1
    `validateName(userName).then(validate => { console.log('validate:', validate); });` – Patrick Roberts Jul 12 '18 at 21:15
  • const validate = *await* validateName(userName). You have to either await an async function or use the promise patter of .then like @PatrickRoberts pointed out. – Adam H Jul 12 '18 at 21:29
  • 1
    @AdamH I would have said that, but based on the given `import` statement, `await` is not valid there, since that's at the top level. – Patrick Roberts Jul 12 '18 at 21:30
  • 1
    @PatrickRoberts good catch, I didn't notice that – Adam H Jul 12 '18 at 21:31
  • @PatrickRoberts I didn't get what you pointed out about the import statement and await not being valid there. – tsinat Jul 12 '18 at 22:20
  • 1
    @tsinat the `import` statement indicates that you want to invoke an asynchronous function at the top-level scope, which requires you to use the `.then()` syntax in order to resolve it. `await` is only a valid statement in the immediate scope of an `async` function. – Patrick Roberts Jul 12 '18 at 22:25

0 Answers0