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.