#mysql #node.js #reactjs #sequelize.js
#mysql #node.js #reactjs #sequelize.js
Вопрос:
У меня есть цикл, в котором я проверяю, существуют ли записи, и если я их не вставляю, проблема в том, что моя консоль показывает код внутри цикла, который не выполняется построчно, сначала он выполняет все выборки, а затем запускает все вставки цикла из Excel
tablesdata.map(async function (table) {
check if record exist
await product_meta
.count({
where: [
{
title: fr_name,
language_id: 2,
},
],
})
.then((count) => {
console.log(count);
if (count > 0) {
console.log(count);
} else {
insert record create_pr = products.create(product, {});product_id = create_pr.id;
}
)}
)}
Ответ №1:
Это будет более просто в использовании async/await
— Array.map()
возвращает массив обещаний, которые могут быть разрешены с помощью Promise.all()
.
const promises = tablesdata.map(async function (table) {
if (recordExists) {
const count = await product_meta.count({
where: {
title: fr_name,
language_id: 2,
},
});
if (!count) {
// this will create a new product, perhaps it is meant to be a product meta?
const create_pr = await products.create(product, {});
// return the created ID
return create_pr.id;
}
console.log("there are already", count, "product metas");
return null;
}
});
// this will resolve an array of newly created IDs,
const allResults = await Promise.all(promises);
// filter out the null entries
const productIds = allResults.filter((result) => result);