循环查询在节点js中续集
Loop queries sequilze in node js
我有一个循环,我正在检查记录是否存在,如果不存在则插入它,问题是我的控制台显示循环内的代码不是逐行 运行,而是 运行s全部先选择然后 运行 所有插入
从 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;
}
)}
)}
使用 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);
我有一个循环,我正在检查记录是否存在,如果不存在则插入它,问题是我的控制台显示循环内的代码不是逐行 运行,而是 运行s全部先选择然后 运行 所有插入 从 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;
}
)}
)}
使用 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);