How can I make this async/.then code work?

I am having issues fully grasping the Promise and Async aspects of the backend in wix. I have the following code that isn’t in the proper sync:

Code on the frontend:

confirmPokemonId($w('#input1'))
.then( (results) => {
wixLocation.to("/searched-pokemon-1/" + results.items[0].title);
});

Code on the backend:

export async function confirmPokemonId(input) {
    let temp = await wixData.query("SearchedPokemon").eq("pokemonId", input.value).find();
    if(temp.items.length > 0) {
        return temp;
    } else {
        let obj = await apiCall("pokemon", input.value);
        return await addPokemon(obj);
    }
}

export function addPokemon(obj) {
...code removed for brevity...
    
    return wixData.query("SearchedPokemon")
    .eq("title", item.title)
    .find(options)
    .then( (results) => {
        if(results.items.length > 0) {
            return results;
        } else {
            return wixData.insert("SearchedPokemon", item, options)
            .then( temp => temp);
        }
    });
}

What am I doing wrong? I have two theories. Either I don’t understand what WixData.insert returns. Or WixLocation is executing before the Pokemon is added to the Database.

The result of wixData.insert() is not an array but a single object.
So you cannot do: results.items[0].title.
Instead you should use: results.title.

Also it’s not clear what you’re trying to do there.
You first retrieve the item then you don’t change it but re-inset it? What’s the point?

  • I don’t see where you define the variable “options” (maybe it’s in the code you removed)

No I’m making sure the item isn’t in the dataset. If it is then I don’t add another copy. If it isn’t then I add it to the dataset. Options is in the removed code, it isn’t related to issue.

Thank you. That sounds like the problem. I will try that and let you know if it works.

This was my problem. Thank you very much!