Dov Alperin
Dov Alperin

Reputation: 39

Calling async function from within async function returns undefined

(Forgive me if the title is inaccurate to the problem this one is boggling the mind) My application requires that I check a value from the request against the database. For this I created an asynchronous function to query the database:

async function checktoken(){
    return prisma.$exists.invalidtoken({token: "testtoken"}).then(result => {
        return(result)
    })
}

I know that the database call on its own works:

prisma.$exists.invalidtoken({token: "testtoken"}).then(result => {
    console.log(result) // returns true 
})

In the function that fires at every request I try and call checktoken():

async function getUser(token){
    var promise = await checktoken()
    var result = promise 
    console.log(result) //undefined
};

Amending the function to include an explicit call to the database works but only when var promise = await checktoken() is defined before it:

async function getUser(token){
    var promise = await checktoken() //When this is removed result1 is undefinded

    await prisma.$exists.invalidtoken({token: "testtoken"}).then(result1 => {
        console.log("inside db call: "+result1) // true
    })
};

I think I have a fundamental misunderstanding of async/await but I am not sure exactly what I am missing.

EDIT: I have updated my approach taking the advice I received and it still does not work. I am beginning to think my ORM is doing something weird:

async function test(token) {
    const status = await prisma.$exists.invalidtoken({ token: token });
    console.log(status);
    return status;
}

test("123") //logs false (as it should)

async function getUser(token){
    var status = await test(token) //logs undefined
    console.log(status) //logs undefined
};

Upvotes: 1

Views: 687

Answers (1)

Jamieson Rhyne
Jamieson Rhyne

Reputation: 467

An async function requires an await. If you are using the promise.then() technique, then what you would want to do is return a new Promise(), and within the .then call back function resolve the promise

function checktoken() { 
    return new Promise((resolve,reject) => {
        prisma.$exists.invalidtoken({token: "testtoken"}).then(result => { 
            doSomeOtherStuff();
            resolve(result);
        });
    });
}

Is functionally the same as

async checktoken() {
    await prisma.$exists.invalidtoken({token: "testtoken"});
}

Upvotes: 1

Related Questions