bla
bla

Reputation: 1055

Unexpected token user = await User.create(user) when i try to create a new user

I'm trying to create a new user using node.js/adonis

I create this two functions:

const User = use("App/Models/User")

async store ({ request, auth }){

    let user = new User()
    user = request.all()

    this.userLogged(auth).then(res => { 
        user.user_id = res.id
        console.log(user)
        user = await User.create(user)
        const token = await auth.generate(user)
        Object.assign(user, token)
        return user
    })
}

async userLogged(auth) {
    try {
        return await auth.getUser()
    } catch (error) {
        console.log(error)
    }
}

The function "userLogged()" return the user that i receive the token in the authorization header.

So i try:

create a new instance of User;
put the request data in this instance;
take the user_id of the authorization header and put in the user.user_id;
create the user with the user_id;
take the token of the registred user;
put in the object user the token;
return the user;

but i'm receiving:

Unexpected token user = await User.create(user)

Upvotes: 0

Views: 1438

Answers (1)

EddieDean
EddieDean

Reputation: 1816

You are attempting to await something not in an async function, specifically the callback in your promise resolver .then.

async store ({ request, auth }){

    let user = new User()
    user = request.all()

    this.userLogged(auth).then(async res => { 
        user.user_id = res.id
        console.log(user)
        user = await User.create(user)
        const token = await auth.generate(user)
        Object.assign(user, token)
        return user
    })
}

Also, based on the code provided, store does not need to be async since you're not awaiting anything at the top level of its scope.

Upvotes: 5

Related Questions