I have an async function processWaitingList() that needs to wait for the result of another function findOpenVillage() that gets it's data from my database.
I'm getting the following error and do not understand why:
(node:2620) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined at processWaitingList (xx\server.js:151:36) at process._tickCallback (internal/process/next_tick.js:68:7) (node:2620) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
I've read everything I can find on promises, callbacks, async and await, but I just cannot figure out how these work.
function slowServerLoop() {
processWaitingList();
}
setInterval(slowServerLoop, 500);
async function processWaitingList() {
let openVillage = await findOpenVillage();
villageId = openVillage[0];
openSpots = openVillage[1];
addPlayerToVillage(waitingList[0], villageId, openSpots);
}
function findOpenVillage() {
con.query(`SELECT id, maxVillagers FROM villages WHERE status='0'`, function (err, result, fields) {
if (err) throw err;
if (result.length === 1) {
let villageId = result[0].id;
let maxVillagers = result[0].maxVillagers;
con.query(`SELECT COUNT(*) as villagerCount FROM villagers WHERE villageId='${villageId}'`, function (err, result, fields) {
if (err) throw err;
let villagerCount = result[0].villagerCount;
let openSpots = maxVillagers - villagerCount;
return [villageId, openSpots];
});
}
});
}