Search code examples
javascriptreactjsnext.jsfetch

Nextjs: running code after complete fetch


This is my code:

async function checkAuth() {
    console.log("3")
    await fetch(apiUrl+'/auth', {
        method: 'POST'
    }).then(response => response.json()).then(result => {
        console.log("5")
    }).catch(error => {
        console.log("6")
    })
    console.log("4")
}

function getFirstData() {
    console.log("1");
    checkAuth()
    console.log("2");
}

I want to checkAuth() run first, and after finish it, another code will be run.

So, my result should be: 13542

But my code not work


Solution

  • try this.

    async function getFirstData() {
        console.log("1");
        await checkAuth()
        console.log("2");
    }