如何使循环等待/异步?

时间:2019-12-03 20:18:15

标签: javascript node.js asynchronous

我知道在StackOverflow上还有更多类似的问题,但是我读了其中的一些,它们都非常具体,我无法解决。因此,我很抱歉提前发布了“重复副本”,但我确实需要帮助。

我做了这个程序,将数据从JSON文件上传到WooCommerce API,但是当我像这样运行它时,由于异步代码不符合我的for循环,它将崩溃。我该如何使其自动化或使for循环同步?这是否有可能,或者还有另一种方式?我要谈论的循环是最后一个循环,uploadAllProducts。

这是代码:

// Import required modules
let fs = require("fs");
const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;

// Connect to WooCommerce's API
const WooCommerce = new WooCommerceRestApi({
  url: '====================',
  consumerKey: "===================",
  consumerSecret: "=====================",
  version: 'wc/v3'
});

async function uploadProducts(page) {

    // Choose a JSON file to import
    let productsJSON = await JSON.parse(fs.readFileSync(`products${page}.json`));
    console.log(`Imported page ${page}`);

    // Iterate over all the products
    productsJSON.forEach(async function(product) {

      // If product is found
      if (product) {
        async function getCategory(a) {
          switch (a) {
            case "film":
              return 202;
              break;
            case "cd vinyl":
              return 163;
              break;
            case "boeken":
              return 133;
              break;
            case "audiovideo":
              return 125;
              break;
            case "baby":
              return 130;
              break;
            case "computer":
              return 190;
              break;
            case "kleding":
              return 205;
              break;
            case "muziek":
              return 208;
              break;
            case "verzamelen":
              return 211;
              break;
            default:
              return 15;
          }
        }

        let cat = await getCategory(product.category);

        async function getsubCategory(b) {
          switch (b) {
            case "dvd films":
              return 203;
              break;
            case "geschiedenis":
              return 138;
              break;
            case "religie":
              return 140;
              break;
            case "thrillers":
              return 141;
              break;
            case "flora fauna":
              return 143;
              break;
            case "detectives":
              return 144;
              break;
            case "dance house":
              return 180;
              break;
            case "software spellen":
              return 191;
              break;
            case "nintendo ds":
              return 192;
              break;
            case "sony playstation":
              return 193;
              break;
            case "nintendo wii":
              return 198;
              break;
            default:
              return 213;
          }
        }

        let subcat = await getsubCategory(product.subcategory);

        // Assign productinformation to WooCommerce product
        const data = await {
          name: product.title,
          type: "simple",
          regular_price: product.price.toString(),
          description: "",
          short_description: product.descr,
          categories: [{
              id: cat
            },
            {
              id: subcat
            }
          ],
          images: [{
            src: product.imgUrl
          }]
        };
        console.log("Assigned all product information");

        // Add product to WooCommerce
        WooCommerce.post("products", data)
          .then((response) => {
            console.log("Product uploaded");
          })
          .catch((error) => {
            console.log(error.response.data);
          });
      }
    });
}

uploadAllProducts(firstPage, lastPage) {
  for (let i = firstPage; i < lastPage + 1; i++) {
    uploadProducts(i);
  }
}

1 个答案:

答案 0 :(得分:0)

如果要使for循环同步,可以执行以下操作:

async function uploadAllProducts(firstPage, lastPage) {
  for (let i = firstPage; i < lastPage + 1; i++) {
    await uploadProducts(i);
  }
}

uploadAllProducts()

您可能还想将WooCommerce.post部分更改为使用await,这样才能正确等待(异步功能中无需在此处使用promises)

let response = await WooCommerce.post("products", data);
console.log("Product uploaded");