Search code examples
javascriptecmascript-6async-awaites6-promise

Why doesn't the code after "await" in this JavaScript ES6 example get run?


I have the following snippet:

let zxcv = () => new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log(4)
    }, 1000)
})

async function jk(){
    await zxcv()
    console.log(6)
}

jk()

When I run this snippet, it waits for a second, then logs "4", then ends. "6" never gets logged.

Why?


Solution

  • You never resolved your promise in zxcv:

    let zxcv = () => new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(4)
            resolve()
        }, 1000)
    })
    

    Otherwise the promise will hang indefinitely!