1

Trying to learn async/await, The below code, awaits on getUserName() to return userName after 2s. hasUser (returns a promise) then just logs the received username.

The problem is console.log(msg) inside the then method logs undefined.

function getUserName() {
    setTimeout(() => {
        return 'Appu'
    },2000)
}

var hasUser= async() => {
        var a = await getUserName()
        return a
    }

hasUser().then((msg) => {
    console.log(msg)
})

Not sure what is the problem here. Appreciate explaining what actually is going on here.

Thanks.

appu
  • 471
  • 1
  • 8
  • 26
  • 2
    Possible duplicate of [Get return value from setTimeout](https://stackoverflow.com/questions/24928846/get-return-value-from-settimeout) – Scott May 30 '19 at 18:02
  • 1
    getUserName is not returning a Promise. And setTimeout doesn't return a promise, so you'll have to translate from its callback pattern into a promise. The accepted answer on Scott's link shows how to do that. – StriplingWarrior May 30 '19 at 18:03

1 Answers1

4

hasUser does not return a promise. You try to await getUserName() but that doesn't return a promise either. If you want to await getUsername() you need to make getUserName return a promise

function getUserName() {
    return new Promise((resolve, reject) => {
       setTimeout(() => {
          resolve('Appu')
       },2000)
    })
}
Isaac Vidrine
  • 1,568
  • 1
  • 8
  • 20