Tuesday, 2 November 2021

Javascript await will only make its current scope async function sync

https://stackoverflow.com/questions/41976606/how-to-await-an-async-call-in-javascript-in-a-synchronous-function

// await make async function sync

 async function asyncExample () {

    try {
        const response = await myPromise()

        // the code here will wait for the 
        // promise to fullfil
    } catch (error) {
        // the code here will execute if the promise fails
    }
}

// await will not make function sync

function nonAsyncExample () {
    asyncExample () 

    console.log('this will not wait for the async to finish')
    // as it's not wrapped in an async function itself
}

No comments:

Post a Comment