简体   繁体   中英

Why await does not wait for setTimeOut

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.

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)
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM