javascriptnode.jsasynchronousasync-awaitecmascript-2017

Is it possible to use await outside async function


This is my simple function in nodejs

const myFunction = async() => {
    const exercises = await Exercise.find({ workoutId })
    return exercises
}

const value = await myFunction()

But when I do await outside async function it throws an error

 await is a reserved word

Now how do I wait for the value outside the async function? Do I need to use callback or .then? Then what is the use async and await?


Solution

  • You can't use await outside an async function. one trick to 'bypass' this limit is to use async IFEE:

    const myFunction = async() => {
        const exercises = await Exercise.find({ workoutId })
        return exercises
    };
    
    (async () => {
        const value = await myFunction()
    })()