I'm having an issue where I want to wait for a async database query and it's operations before I continue.
I could of course put operations inside a pyramid, but it won't be cool on the long run, because I will have to duplicate code some of the times.
Here is my example (that will of course not work currently, because of async on database queries):
var level = 5;
var difficulty = 30; //example
let randomDecider = Math.floor(Math.random()*(50+level)+1);
if (difficulty < randomDecider) {
var type;
var name;
var heroid = "";
dbconn.query("SELECT * FROM owned_heroes WHERE user = ? AND equipped = 1", [req.session.login], function(err, result, fields) {
heroid = result[0].heroid;
});
if (randomDecider > 50) {
type = "skill";
var ownedSkills = [];
var skillsKeys = Object.keys(Skill);
dbconn.query("SELECT * FROM owned_skills WHERE user = ? AND heroid = ? AND equipped = 1", [req.session.login, heroid], function(err, result, fields) {
for (var i = 0; i < result.length; i++) {
ownedSkills.push(result[i].name);
}
});
//Here later I also want to remove ownedSkills from skillsKeys.
name = skillsKeys[Math.floor(Math.random()*skillsKeys.length)];
}
else {
type = "item";
var itemsKeys = Object.keys(Item);
var ownedItems = [];
dbconn.query("SELECT * FROM owned_items WHERE user = ? AND heroid = ? AND equipped = 1", [req.session.login, heroid], function(err, result, fields) {
for (var i = 0; i < result.length; i++) {
ownedItems.push(result[i].name);
}
});
//Here later I also want to remove ownedItems from itemsKeys.
name = itemsKeys[Math.floor(Math.random()*itemsKeys.length)];
}
//Some other code using the type and name variable.
So could someone based on this explain me how would I convert this into something working, like waiting for the actions after queries to complete before going forward. I tried async/await, but I couldn't figure it out currently.
Also any other suggestions to the code is highly welcome.
Thanks.
Promises. It can allow you to avoid the callback pyramid hell while solving your problem. You can try wrapping the query function into Promises.function q(str, params) { return new Promise((resolve, reject) => {dbconn.query(str, params, (err, result, fields) => {if (err) reject(err); resolve(result)})})}. I have came up with an answer using this if you don't mind to wait a little more.