javascript - for-of 循环和异步函数的问题
问题描述
我想等到我的函数 checkNumber() 完成并返回结果。不幸的是,for-off 循环不会等待函数并在开始时进行所有迭代。我尝试了许多与 async/await 的组合,但没有一个真正起作用。当我运行这个函数时,它会打印出与循环一样多的 console.log("start error"),然后我得到 productList。当 checkNumber() 返回错误时,我想停止 for 循环。
主功能:
if (!req.body) {
res.status(400).send({
message: "Values can not be empty!"
});
}
console.log("list of products: ", req.body.product);
const productArr = req.body.product; //array of products retrieved from json
let productList = [];
let quantityList = [];
let error = 0;
for (const product of productArr) { //iterate through products
console.log("start error: ", error); // <----
if (error == 1) {
console.log("stop");
break;
}
//check if product's vat exists in vat table, if not add new
Vat.checkNumber(product.vat, async function (err, data) {
console.log("result: ", data);
if (!data) {
console.log("not found");
console.log(err);
error = 1;
} else {
console.log("found");
const vat_id = data;
//crete new product obj json
let newProduct = {
vat_id: vat_id,
name: product.name,
price: product.price
};
//store product list and their quantity to use later in sql query
productList.push(newProduct);
quantityList.push(product.quantity);
console.log(productList);
console.log(quantityList);
}
});
}
}
增值税功能:
sql.query("SELECT * FROM vat where number = ?", number, function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length <= 0) {
err = "Vat cannot be null";
result({ error: "Vat not found" }, null);
return;
}
console.log("Found vat: ", res[0].id);
result(null, res[0].id);
return;
});
};
解决方案
试试这个:
async function checkNumber(number) {
return new Promise((resolve, reject) => {
sql.query('SELECT * FROM vat where number = ?', number, function(err, res) {
if (err) {
console.log('error: ', err);
reject(err);
return;
}
if (res.length <= 0) {
err = 'Vat cannot be null';
reject({ error: 'Vat not found' });
return;
}
console.log('Found vat: ', res[0].id);
resolve(res[0].id);
});
});
}
进而
for (const product of productArr) { //iterate through products
console.log("start error: ", error); // <----
if (error == 1) {
console.log("stop");
break;
}
//check if product's vat exists in vat table, if not add new
let data;
try {
data = await checkNumberPromisified(product.vat);
if (!data) {
console.log("not found");
error = 1;
} else {
console.log("found");
const vat_id = data;
//crete new product obj json
let newProduct = {
vat_id: vat_id,
name: product.name,
price: product.price
};
//store product list and their quantity to use later in sql query
productList.push(newProduct);
quantityList.push(product.quantity);
console.log(productList);
console.log(quantityList);
}
}
catch (err) {
console.log(err);
error = 1;
}
}
推荐阅读
- bash - 如何在 bash 脚本中标记邮件?
- typescript - 让 VSCode Marketplace 更新自述文件
- python - 从 Json 输出检查 dict (urllib2)
- javascript - 动态子内容上的 MutationObserver
- dataframe - 我们如何在 spark scala 中将 (a1|a2|a3 b1|b2|b3) 更改为 ((a1,a2,a3),(b1,b2,b3))
- angular - 在 Angular 8 应用程序中的 AppComponent_Host ngfactory js 中出现错误 [object Object]
- python - 将 datetime64[ns, UTC] 隐蔽到 datetime64 python
- billboard.js - 如何在 billboardJS 中使用转换日期
- curl - 客户端证书可以在标头中发送吗?
- sql - 如何更新此选择查询以更新?- 到目前为止,它只是挂起