I recently started working with node and despite having read a lot about it I still have difficulties working with asynchronism concepts. I have the following scenario:
const mysql = require("mysql");
exports.mainFunction = () => {
productsArray = ['product 1', 'product 2', 'n...']; // A simple product array
createLogFile();
proccessProducts(productsArray);
/* HERE I NEED TO RETURN "OK" WHEN BOTH FUNCTIONS (createLogFile and proccessProducts) ARE FINISHED
BUT HOW DO YOU KNOW WHEN THEY WERE FINISHED? */
}
const createLogFile = (logFileName) => {
fs.writeFileSync("mylog.json", "") // Here I create a simple log file for future use.
}
const proccessProducts(productsArray) = {
for (let p = 0; p < productsArray.length; p++) { // Here I iterate over the products array
const newProduct = formatProduct(productsArray[p]); // Here I make some formatting in the product title
saveProductInDatabase(newProduct); // And lastly I save the product in the database
}
}
const saveProductToDataBase = (product) => {
var connection = mysql.createPool({
host: config.MYSQL_HOST,
user: config.MYSQL_USER,
password: config.MYSQL_PASSWORD,
database: config.MYSQL_DB,
});
const query = "INSERT INTO products(Title) VALUES (?)"
connection.query(query, product, (err) => {
if (err) console.log(err)
});
}
const formatProduct = (product) => {
var productTitleList = product.split(" ")
return productTitleList[1]
}
My difficulty here is to know when everything has already been executed in order to return an "ok" status in the main function... I don't exactly know how to work with promises and async/await in this environment. Could someone give me a light?