提问者:小点点

for-of循环和异步函数的问题


我想等到我的函数checkNumber()完成并返回结果。不幸的是,for-off循环并不等待函数,而是在开始时执行所有的迭代。我尝试了许多与Async/Await的组合,但没有一个真正有效。当我运行这个函数时,它打印出与循环一样多的console.log(“start error”),然后我得到ProductList。我希望在checkNumber()返回错误时停止循环。

主要功能:

  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;
  });
};

共1个答案

匿名用户

请尝试以下操作:

const util = require('util');
const checkNumberPromisified = util.promisify(Vat.checkNumber);

  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 = await checkNumberPromisyfied(product.vat);      
    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);
      }
  }

相关问题