Nextjs: running code after complete fetch

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Nextjs: running code after complete fetch on this date .

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

Answer

try this.

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