0

I know there are more questions like this on StackOverflow, but I read a few of them and they're all pretty specific and I can't work it out. So I'm sorry in advance for posting a "duplicate", but I really need help.

I made this program to upload data from a JSON file to the WooCommerce API, but when I run it like this it will crash because of the asynchronous code not keeping up with my for loop. How can I automate this, or make the for-loop synchronous? Is that even possible or it there another way? The loop I'm talking about is the one right at the end, uploadAllProducts.

This is the code:

// 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);
  }
}
  • I don't see a return in uploadProducts. With async keyword, you have to return in order to resolve the promise. – Cal Irvine Dec 03 '19 at 20:31

1 Answers1

0

If you want to make the for-loop synchronous, you can do something like:

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

uploadAllProducts()

You also probably want to change the WooCommerce.post section to use await like this so it is properly awaited (Theres no need to use promises here inside your async function)

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