Getting Data from A Database Based on fieldkey

My main problem is being able to return what the Promise gives me. How can I get what the Promise gives me (which is the variable results) and access the data outside of the Promise? Below are the details which I tried to lay out as simple as possible.

Another seemingly easy question, but I’m having trouble getting the variable out of the Promise; note I am not experienced with Promises as I never encountered them before Javascript, but I have a fairly good idea of what they are.
Anyways, I am trying to make a function to allow me to retrieve the Data of a particular Dynamic Page. Here is the Code I am using:

let pageid = the unique ID of the Database Element (which appears at the end of the page URL); 

export function GetData(fieldkey) //note: fieldkey is the column of the //Database 
{
    wixData.get("Collection", pageid) 
    .then( (results) => {
    //gets the data of the Element in the Database 
    let item = results; 
    
    //output is the ideal return I'd like to get. 
    //var output = results[String(fieldkey)]; 
    
    //console logs showing the output; return doesn't seem to be working 
    //at all 
    console.log(item); 
    console.log(results); 
    //return (output); 
  } )
  
  .catch( (err) => {
    let errorMsg = err; 
    console.log("error"); 
  } ); 

}

//This is calling the Promise result outside of the function; I get "undefined" as an answer in the console log. 
let data = GetData(fieldkey); 

So in laymen’s terms, my goal is to access what the wixData.get() function does like this:

var title = GetData(fieldkey); 
//if fieldkey == "title"; (which I think is the first column id of every Database) 
GetData("title") == the title of the dynamic page's row in the Database. 

Problems:
Within the Scope of the wixData.get() Promise Scope:

  • If I make var output = results[fieldkey], then it gives me undefined.

  • If I make var output = results[“title”], then I get the data I am looking for. (however I can’t get it to return out of the function)
    Outside of the Function:

  • If I call GetData(fieldkey) outside of the function (which should be equivalent to results[fieldkey] within the function), I get undefined.

  • If I call GetData(“title”) outside of the function, I get undefined.

note: I got the variable pageid from wixLocation. path

var DB_ID = "your_DATABASE_ID_here"; 
var DB_FIELD = "your_DB_FIELD_here";

let myRequestResult = get_BackendData(DB_ID, DB_FIELD); 
console.log(myRequestResult);
 

export function get_BackendData(DB_ID, DB_FIELD){
    return wixData.get(DB_ID, DB_FIELD) 
    .then( (res) => {console.log("Res: ", res);
        let items = res; console.log("Items: ", items); 
	return(items);
    }).catch((err)=>{console.log("ERROR: ", err); return(err);}); 
}

Why it is an EXPORT function?
-Is your function not located on the same page? Backend?

@russian-dima technically no, I just have a habit of adding that since it automatically adds it when creating event handlers :P.
Thanks for responding, I tried out your code and I got the same thing I did with the code above: I got the JSON list of items but when the res and items were commented, I got NULL.
The wixData.get() gives me a JSON formatted like this:

My base question is: How could I access these elements? Within the Promise I could do result[“title”] to give me the value of the title, but I can’t seem to access this outside of the Promise Scope, and also if I did:

function GetData(collection, itemid) 
{
  wixData.get(collection, itemid)
  .then( (results) => {
    let item = results; 
    //inside of scope: 
    console.log(item); //shows nothing. 
    console.log(results); //returns the Data I want. 
    console.log(item["title"]); //Returns What I want 
    console.log(results["title"]); //Returns What I Want. 
    var tit = "title"; 
    console.log(item[tit]); //Returns What I Want. 
    console.log(results[tit]); //Returns What I Want. . 
    return (item); //returns the Data I want. 
    
  } )
}
//Outside of Scope: 
console.log("A " + GetData("MyCollection", itemid)); //Returns What I Want. . 
console.log("A " + GetData("MyCollection", itemid)["title"]); //I cannot access "title" outside of function/Promise Scope. 

Getting the List of data is useless if I don’t know how to access the data in it outside the Promise. :frowning:

@josephchancewatkins
DAMN! Sorry —> MY FAULT !

My code was not complete! I forgot something…try this one…

var DB_ID = "your_DATABASE_ID_here"; 
var DB_FIELD = "your_DB_FIELD_here";

let myRequestResult = await get_BackendData(DB_ID, DB_FIELD); 
console.log(myRequestResult);
 

export function get_BackendData(DB_ID, DB_FIELD){
    return wixData.get(DB_ID, DB_FIELD) 
    .then( (res) => {console.log("Res: ", res);
        let items = res; console.log("Items: ", items); 
    return(items);
    }).catch((err)=>{console.log("ERROR: ", err); return(err);}); 
}

ADDITIONAL-INFO: Add → async ← to your onReady-Code-Part!

Or if you do not want to use async-await, you can do it with a → .then(()=>{}-method

get_BackendData(DB_ID, DB_FIELD).then((res)=>{console.log(res);}); 

I think the rest will be clear for you, it seems you are not a total beginner.

BTW: Not sure if this return is neccessary at this line:

return wixData.get(DB_ID,DB_FIELD)

Test it out!

@russian-dima Thanks for the response, however I am still trying to find out how to make use of the Function.

const data = wixData.get("Collection", itemid)
  .then( (results) => {
    let output = results; 
    return output; 
  } ); 

console.log(data); 

I’m such a noob at Promises :P. Okay so this is the basic function. Could you show me how to use async to get the data? I’ve tried this:

const o = async () => { 
        const a = await output; 
        console.log(a); 

But it doesn’t work. If I were to just return:
console.log(data);
Then I get the return “Promise<>”.
I been at this for at least 12 hours XD; Promises are so confusing.

@josephchancewatkins

Something is wrong in your logic or in mine xD

Ok, look at this simple example!

You start like always with this one…–> you put the rest of your code inside this one…

$w.onReady(function() { ....... });

For example your code here →

const data = wixData.get("Collection", itemid)
 .then( (results) => {
    let output = results; 
    return output; 
}); 

—> turning into a function…

function yourFunction() {
  const data = wixData.get("Collection", itemid)
  .then( (results) => {
    let output = results; 
    return output; 
  }); 
}

—>after doing little corrections…

function yourFunction() {
  const data = wixData.get("Collection", itemid)
  data.find()
  .then((results)=>{return results;})
  .catcht((error)=>{return(error)}); 
}

First part-result would be something like this…

Till here everything clear? What do you think, would this already work?

import wixData from 'wix-data';

$w.onReady(function(){
    let DATABASE = "hereYourCollectionID"   //example-collection-ID
    let itemID = "123213213213213213213"    //example-itemID

    yourFunction(DATABASE, itemID);         // <----starting your function here
    // or doing the same with direct-value-injection....
    yourFunction("hereYourCollectionID", "123213213213213213213"); 
});

function yourFunction(DATABASE, itemid) {
  wixData.get(DATABASE, itemid)
  .then((results)=>{return results;}) //<<--- this here is the important part!
  .catch((error)=>{return(error)}); 
}

Doing it like shown above, you will surely get one more time → an unresolved PROMISE!

So do we still missing? We still have to wait for our RESULTS from the function!
Doing the following steps and upgrading our code, either by an usage of :

  1. ASYNC-AWAIT
    …or…
  2. THEN-METHOD

Let’s do it with async-await → my favourite one…

import wixData from 'wix-data';

$w.onReady(function(){
    let DATABASE = "hereYourCollectionID"   //example-collection-ID
    let itemID = "123213213213213213213"    //example-itemID

    let myRESULTS = awaityourFunction(DATABASE, itemID);// <--starting your function here
    //that means --> only when --> myRESULTS <-- are ready --> you will get the OUTPUT
    //OUTPUT
    console.log(myRESULTS)
});

function yourFunction(DATABASE, itemid) {
  wixData.get(DATABASE, itemid)
  .then((results)=>{return results;}) //<<--- this here is the important part!
  .catch((error)=>{return(error)}); 
}

And the last additional step would be to add → “async” to the right place of our generated code…

$w.onReady(async function(){..........

Our END-RESULT-FUNCTION…

import wixData from 'wix-data';

$w.onReady(async function(){
    let DATABASE = "CollectionID"   
    let itemID = "itemID"    
    let myRESULTS = await yourFunction(DATABASE, itemID); console.log(myRESULTS)
});

function yourFunction(DATABASE, itemid) {
  wixData.get(DATABASE, itemid)
  .then((results)=>{return results;}) //<<--- this here is the important part!
  .catch((error)=>{return(error)}); 
}

The only thing where i also have to test it, or where i am also not always 100% sure, is this one…
without an extra RETURN…

 wixData.get(DATABASE, itemid)

…or with an extra return…

 return wixData.get(DATABASE, itemid)

Thats it!

1 Like

@russian-dima thanks, I was really wracking my brain trying to understand async. I had been looking at Javascript tutorials and documentation all night last night XD. I’m going to see if I can get a result when I get on my PC, cuz accessing database data is extremely important in my site.

1 Like

@josephchancewatkins
The most important thing on your site will ALWAYS be your DATABASES and their STRUCTURE. A SITE without a DATABASE is not a site, it’s something else, but not a real Website.

…cuz accessing database data is extremely important in my site.

And yes! This is one part of working with databases and as you can see, you said it by your own…

—> extremely important in my site

@russian-dima update: So I finally settled on the fact that I can’t get the result outside of the Promise scope, so I did this:

wixData.get("My Collection", id)
  .then( (results) => {
  var t = results.title; 
  $w("#text1").title = t; //String(results.title); 
  console.log(results.title); 
  console.log(results); 
  } )
  .catch( (err) => {
    let errorMsg = err; 
  } );

I am setting the Text of a text equal to the Database item’s title. The Console Log gives me what I want, but the text is not changing. I tried converting it to String and everything. I also tried indexing the results.title on the console log (ex: results.title[0] which gave me the first letter of the title) which confirms it’s a String.
What am I doing wrong? I can’t seem to use the data from this no matter what I do.

Yay! I got it working. I converted the variable t to a string. I think it just took some time to update.

1 Like

@josephchancewatkins Well done!

Hi there,

To access the returned data from a promise, you can either store the value in a higher scoop variable, or you can store the value directly in a variable, I’ll explain both methods.

// The actual promise we need to get the data from
const getData = () => {
    return new Promise(resolve => {
        setTimeout(resolve('Ahmad'), 2e3)
    })
}

Method #1: Store the result in a higher scoop variable.

let answer; // Currently, it's: undefined

// Invoke the function:
await getData().then(x => answer = x);

console.log(answer); // Prints: Ahmad

Method #2: Store the value in a variable, directly (The most common way).

const answer = await getData();

console.log(answer); // Prints: Ahmad

Note: Whenever you use the await keyword, it needs to be inside an async function. Learn more.

Hope this helps~!
Ahmad