I am new to wix and javascript, though with years of experience as a BACKEND engineer w/many languages, including Python & Ruby, interpreted languages that make javascript relatively familiar.
What’s VERY foreign (I have ZERO front-end/UI experience) is the approach, necessary as it is in the browser world, of the way the single thread model supports asynchronicity.
I’m used to a wealth of support for asynchronous/parallel processing through threads.
The Promise mechanism appears to be a ‘SWEET’ solution to the problem of asynchronicity in javascript.
Only I can’t wrap my head around how I deal w/this mechanism to support the need to know when a query has completed. I love the fact that I can launch the query at the start of page load or onReady(), but ALSO in onReady() (or in page load really) I need to be able to get the results of the query to hide/show certain elements based on attributes of a particular user logged in which are stored in my ‘Members’ table.
I get that the ‘then’ method only runs on query completion, AND I’ve seen using the following code that it sometimes completes BEFORE this while loop:
while ( (membersDB[‘val’] === “N/A”) && (indx < 100000000) ) {
and sometimes AFTER, but it appears if it DOESN’T complete before the loop, that no matter how long I wait in the loop (and this IS a VERY simple wait: I’ve used more significant ones using console.log(), etc.) that the query completion DOESN’T complete during the loop. I always get indx = 0 OR indx = whatever limit I set. Sounds like black magic, but THERE MUST BE a better way to wait for the query completion. I’ve seen the discussions of async/await, but I haven’t been able to figure out how to use it.
The query method:
export function getTable(collection, returnObj) {
wixData.query(collection)
.find()
.then( (results) => {
returnObj[‘val’] = results;
returnObj[‘end’] = new Date().getTime();
console.log(“getTable(” + collection + ") returned at " + returnObj[‘end’]);
} )
.catch ( (err) => {
console.error('getTable ERROR: ’ + err);
})
}====================
The code that calls it (starting w/page load):
import {queryTable} from ‘public/db_helper.js’;
let startTime = new Date().getTime();
let membersDB = {‘val’: “N/A”, ‘start’: startTime, ‘end’: null};
getTable(‘Members’, membersDB);
console.log(“firstLoad: membersDB = " + membersDB[‘val’] + " @” + membersDB[‘start’]);
$w.onReady(function () {
var enterTime = new Date().getTime();
console.log("onReady(): userEmail = " + userEmail[‘val’] + “; membersDB = " + membersDB[‘val’] + " @” + enterTime);
var indx = 0;
while ( (membersDB[‘val’] === “N/A”) && (indx < 10000) ) {
indx++;
}
var endTime = new Date().getTime();
console.log("onReady2(): indx = " + indx + "; userEmail = " + userEmail[‘val’] + “; membersDB = " + membersDB[‘val’] + " @” + endTime);