I am trying to generate a unique voucher number on the _beforeInsert hook. I generate a number and try to look it up in the collection if it already exists. If not, generate a new number, until we found a unique one.
Well, I think I am struggling with Promises, because it won´t work as expected. I looked up the articles, put my .then´s and return´s in in the correct place, I think, but I´m doing something wrong.
Console.log 5 & 6 are never displayed. Collection name and field name are correct.
Somebody sees it?
Here is the code (data.js):
import wixData from 'wix-data';
export function Vouchers_beforeInsert(item, context) {
console.log("1: In beforeinsert");
let strRandomNum;
let boolVoucherExists = false;
do {
strRandomNum = getRandomNum(100000, 999999).toString();
console.log("2: strRandomNum after gen=" + strRandomNum);
chkIfExist(strRandomNum)
.then((VoucherExists) => {
boolVoucherExists = VoucherExists;
console.log("6: boolVoucherExists after db-check=" + boolVoucherExists);
});
}
while (boolVoucherExists === true);
console.log("7: Returning number to hook=" + strRandomNum);
item.fldVoucherId = strRandomNum;
return item;
}
function getRandomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function chkIfExist(strRandomNum) {
console.log("3: In chkIfExist");
console.log("4: strRandomNum before query= " + strRandomNum);
return wixData.query("Vouchers")
.eq("fldVoucherId", strRandomNum)
.count()
.then((amount) => {
let numCount = amount;
console.log("5: numCount=" + numCount);
let boolIdExists = (numCount > 0);
return boolIdExists;
})
.catch((err) => {
let errorMsg = err;
console.log("errorMsg=" + errorMsg);
});
}
David, I have taken it all apart and started testing with a first query and a number that already existed. That works well and a new number is generated, tested if that one exists, and returns brilliantly .... if it is wrapped inside an IF statement. But, if I wrap it inside a do-while, the query is NOT executed, not even for the first time. I am clueless. I changed to a new post, here: https://www.wix.com/code/home/forum/questions-answers/if-vs-do-with-promise
Frankly I’d defer my code questions to you, so I’m not overly qualified but I’m just tossing random solutions out there. Have you tried adding an async to vouchers_beforeInsert and an await before getRandomNum.
It’s possinle your query is trying to use getRandomNum before it’s available?
David, thanks, but what you propose goes for a .find, not for a. Count query. I took this query out, put it on a separate page and fed it with a couple of numbers on the button click. Runs perfectly. But here it doesn't, so I think I'm running against some promise problem.
Perhaps too obvious but doesn’t a query return an array of objects so numCount = amount.items as opposed to just amount. Then you could .length that? or if you need the actual field value just do numCount = amount[0]