The Easy way is to use already existing ORM like sequalizejs or etc they return promise for you and instead of running find and create in separate Raw query in native MySQL driver. You can simply use API'S like find or create something.
i explain you how async works in your example , i took a piece of code from your example.
async function createArtist(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
});
}
const artistId = (async () => {
await createArtist('maxi');
})();
look into createArtist function this is exactly what you have . Three things you have to note here,
- you declare it a async function so it return promise in default.
- it can simply return anything like normal function ,if it is a synchronous function avoid using async.
- As you said you cannot return anything from callback . since it is asynchronous you have to return promise.
so the code can be changed to
async function createArtist(artist_name) {
return new Promise((resolve,reject)=>{
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) reject(err);
resolve(result.insertId)
});
});
}
const artistId = (async () => {
await createArtist('maxi');
})();
Things changed here , added native promise wrapper and return it, before it goes asynchronous. called resolve to make success . And reject to make it fail.
Don't forget to add try ...catch blog for await's to handle error.
No comments:
Post a Comment