What I want to accomplish:
- gather artist id`s
- either finding them in the db
- or creating them
- creating an event in the db, getting the event_id
- waiting till both are done, artists and event id`s gathered
- now looping over the artist, event combinations
What I got:
I`m working with Node and mysql. To insert the relations I have to wait for the artists to insert or create. I try to accomplish with the following code:
let promises = [];
if (artists.length != 0) {
for (key in artists) {
promises.push( find_artist_id_or_create_new_artist(artists[key]) )
}
}
await Promise.all(promises);
Returning an id:
async function find_artist_id_or_create_new_artist(artist_name) {
return await find_artist_return_id(artist_name, create_artist_return_id)
}
Finding an artist:
async function find_artist_return_id(artist_name, callback) {
var sql = "SELECT * FROM `artists` WHERE `name` LIKE "+con.escape(artist_name)+" LIMIT 1;"
con.query(sql, (err,row) => {
if(err) throw err;
if (row.length == 0) {
return callback(artist_name)
} else {
return row[0].id
}
});
}
Creating an artist
async function create_artist_return_id(artist_name) {
var sql = "INSERT INTO `artists` (`id`, `name`, `meta_1`, `meta_2`) VALUES (NULL, "+con.escape(artist_name)+", NULL, NULL)";
con.query(sql, (err, result) => {
if(err) throw err;
return result.insertId
});
}
I understand that I cant return in a con.query function, but I dont how to properly setup the code to get this done. A link to, or help how to search for an answer is appreciated.
SQL functions
need to be converted topromises
in order to beawaited
.await
can wait on any Promise,async
is just a means of making a function return aPromise
, but if inside this function you use callbacks you have broken the Promise. So in above if you just using the Promise version of mySQL you would do ->var result = await con.query(sql)
instead, basically the callbacks are not used.