我最近开始使用 node,尽管阅读了很多关于它的内容,但我仍然难以处理异步概念。我有以下场景:
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]
}
我在这里的困难是知道什么时候一切都已经被执行,以便在主函数中返回“ok”状态......我不完全知道如何在这种环境中使用 promises 和 async/await。有人能给我一盏灯吗?
答案 0 :(得分:1)
我没有解释为什么会这样,它是如何工作的,因为有很多资源可以回答这些问题。
var connection = mysql.createPool({
host: config.MYSQL_HOST,
user: config.MYSQL_USER,
password: config.MYSQL_PASSWORD,
database: config.MYSQL_DB,
});
// There is nothing to do asynchronous, becouse `writeFileSync` blocking operation.
function createLogFile(_logFileName) {
fs.writeFileSync("mylog.json", "");
}
// In this example we used `callback`,
// You can think this is main function,
exports.mainFunction = async () => {
try {
let productsArray = ['product 1', 'product 2', 'n...']; // A simple product array
createLogFile();
// async function always return `promise`
await proccessProducts(productsArray);
// include your logic here, when every Products had proccessed.
} catch (error) {
console.log(error);
// handle error.
}
}
// In order to use await keyword, you need async function...
async function proccessProducts(productsArray) {
// Here I iterate over the products array
for (const product of productsArray) {
const newProduct = formatProduct(product); // Here I make some formatting in the product title
// You need to use
await saveProductInDatabase(newProduct); // And lastly I save the product in the database
}
// in this example, results is executed in parallel,
// its OK to use string, bsc javascript ignore string, as like comments
`await Promise.all(
productsArray.map(product => saveProductInDatabase(formatProduct(product)))
);`
}
// return Promise object,
function saveProductInDatabase(product) {
const query = "INSERT INTO products(Title) VALUES (?)";
return new Promise((res, rej) => {
connection.query(query, product, (err, data) => err ? rej(err) : res(data));
});
}
您可以从以下方面获得一些关于 async/await
、回调、承诺的想法: