0

I'm trying to retrieve the _id field with Wix Velo of my logged in user. The code is working, however the function I'm using is returning [object Promise] instead of the id string that I need.

import wixData from 'wix-data';

export function getID() {
    return wixData.query("Picks") // My Collection
        .eq("player", "Gary") // A field, and a cell
        .find()
        .then((results) => {
            if (results.items.length > 0) {
                let firstItem = results.items[0]._id; 
                console.log("Return ID: " + firstItem) // This returns the ID I need
                $w("#text31").text = firstItem;
            //    return firstItem.toString();
            } else {
                console.log("No Items Found")
            }
        })
        .catch((err) => {
            let errorMsg = err;
        });
}
 
console.log("Return the ID outside of the function: " + getID()) // This returns "[object Promise]"

I've tried to use await, but it just gives me errors.

Bob Arnson
  • 21,377
  • 2
  • 40
  • 47
xar86413
  • 119
  • 8

2 Answers2

0

Since top-level-await is not supported by all the browsers, I believe Wix didn't open that feature as well. Instead, wrap it with an async IIFE.

(async () => {
  console.log("Return the ID outside of the function: " + await getID())
})();

This answer has more details about top-level-await

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
0

Just incase this helps someone else, the answer was in nested promises. I had to call the first function getLoggedInUserName() to get the user name, and then pass that to a nested function called getID().

Essentially, this was a scope issue, and also waiting for the promise to be resolved.

getLoggedInUserName().then((results) => {
    let userName = results;

    getID(userName).then((results) => {
        let userID = results;
        let pick = $w("#dropdown1").value;

        let toUpdate = {
            "_id": userID,
            "pick": pick,
            "player": userName,
           
        }
        wixData.update("Picks", toUpdate)
            .then((results) => {
                $w("#text33").show();
                let item = results;
            })
            .catch((err) => {
                let errorMsg = err;
                console.log("Error: " + errorMsg)
            });
    })
})
.catch((err) => {
    let errorMsg = err;
});

xar86413
  • 119
  • 8