Hi,
I am having a very strange problem.
The code:
lang1="00";
level1="00";
wixData.query("Memebers")
.eq("_id", userId)
.find()
.then( (res) => {
console.log(`****results is coming*****`);
console.log(res);
console.log(`****results.items[0] is coming*****`);
console.log(res.items[0]);
console.log(res.items[0].lang1);
lang1 = res.items[0].lang1;
level1 = res.items[0].lang1Level;
console.log(`*lang1:_${lang1}_`);
console.log(`*lang1_level1:_${level1}_`);
} )
.catch( (error) => {
let errorMsg = error.message;
let code = error.code;
} );
console.log(`**lang1: ${lang1}`);
console.log(`**lang1_level: ${level1}`);
===============================================
the result is that **lang1 is executed BEFORE *lang1 which messes my entire code. any thougts?
log:
**lang1: 00
wixcode-worker.js:1:42389
**lang1_level: 00
wixcode-worker.js:1:42389
****results is coming*****
wixcode-worker.js:1:42389
Object { _items: […], _totalCount: 1, _query: {…}, nextSkipNumber: 1, prevSkipNumber: -50 }
wixcode-worker.js:1:42389
****results.items[0] is coming*****
wixcode-worker.js:1:42389
Object { _id: "6fd64fb4-37ba-4855-94a6-2ea0b416d1e2", email: "te … }
wixcode-worker.js:1:42389
fr
wixcode-worker.js:1:42389
*lang1:_fr_
wixcode-worker.js:1:42389
*lang1_level1:_M_
Thank you. I read the API before posting...I think the API should mention the async part. To my view, saying in the documentation it is a Promise is not sufficient.
The relevant API reference can be found here: https://www.wix.com/code/reference/wix-data.WixDataQuery.html#find
Thanks. I figured that out already. I think your WixData documentation should indicate that.
Hi erezsh,
The wixData "find" method returns a Promise object, which means that the function you pass to its "then" method will be called some time in the future when the asynchronous operation (going to the DB to get the data) completes.
So when calling "then" you just register the callback, and it does not execute immediately.
The next thing you do after registering the callback, is logging the ** lines and that executes immediately, so those lines get printed first.
(see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise for more info on Promises)