Wait for fetch to resolve

I assumed that

let MyData = await createMyData(googleID, curItem);
console.log("2: " + MyData);

leads to createMyData being executed first :thinking:

But it’s bedtime in good ol’ Germany. :zzz:
Maybe I’ll figure it out tomorrow…

Thanks for your great help!

Spectral

Last one for you, to let explode your brain totaly :joy:

To make your function more efficient and capable of handling multiple data entries in a more structured manner, you can utilize async/await along with Promise.all() to wait for all asynchronous operations to complete before returning the final itemData array. Additionally, you can use a more organized approach by defining an array of data types you want to fetch and process, and iterate through them to handle each type of data dynamically. Here’s a revised version of your function:

This is now modified by C-GPT: → regarding the await-problem.
Sounds plausible, but you will have to test it on your own, whats best for you and which of all approaches you understand the best!

async function createItemData(googleID, curItem) {
    let itemData = [];

    if (googleID) {
        try {
            const response = await fetchData(googleID);
            itemData = await processItemData(response, curItem);
        } catch (error) {
            console.error("Error fetching data:", error);
        }
    } else {
        itemData = await processItemData(null, curItem);
    }

    console.log("1: " + itemData);
    return itemData;
}

async function processItemData(response, curItem) {
    let itemID = "0";
    let itemData = [];

    const dataTypes = [
        { key: "formattedAddress", label: "Address:" },
        // Add more data types as needed
    ];

    for (const dataType of dataTypes) {
        let value = null;
        if (response && response[dataType.key]) {
            value = response[dataType.key];
        } else if (curItem[dataType.key]) {
            value = curItem[dataType.key];
        }

        if (value !== null) {
            itemID = writeDataToArray(itemID, dataType.label, value, itemData);
        }
    }

    return itemData;
}

function writeDataToArray(id, label, value, dataArray) {
    // Implement your logic to write data to the array
    // For example:
    dataArray.push({ id, label, value });
    return id; // Return the updated ID
}

In this version:

  1. createItemData function now utilizes async/await and try-catch blocks for better asynchronous handling.
  2. The processItemData function is introduced to handle the processing of data entries dynamically. It iterates through an array of data types and extracts the corresponding data from either the response or the curItem.
  3. The writeDataToArray function is used to write data to the itemData array. You can customize this function according to your data structure requirements.

Like i am always saying → there are many roads leading you to success.
All you have to do is → to work on it.

1 Like

Thanks, I have also asked C-GPT and got a hint about the Promise of the function. But before my brain bursts, I’d better go to bed now and continue testing tomorrow :grinning:

1 Like

Hi @russian-dima

maybe it was worth sleeping on it, at least I realised today what I hadn’t understood before. I assumed it was enough to call a function with await and everything in the function is then processed before a promise is returned - of course this is not the case. That’s why createMyData didn’t wait for the fetch and returned a Promise beforehand.

I have now moved createMyData to the backend and added a catch block with a response and an await before the fetch. The code is then processed in the desired order.

Thanks to the optimisations you suggested, the code in the frontend has been reduced from 740 lines to 375 lines and there are more than 200 lines of code less in total.

The only drawback is that the Google Search Console still shows an empty repeater in the screenshot of the live page test. But it is known that Googlebot has difficulties rendering JavaScript (and it costs more money) and delays possibly rendering of JavaScript beyond its initial URL discovery.

Maybe I’ll fetch the data cyclically into my own database and can do without the live fetch. A real-time query (“open now?”) would then of course no longer be possible, but the performance would probably also be better. Let’s see…

Many thanks for your (time-consuming) and excellent help!

2 Likes

Thanks to the optimisations you suggested, the code in the frontend has been reduced from 740 lines to 375 lines and there are more than 200 lines of code less in total.

This i like!

Surely you can reduce even more, but it’s on you.
If the code is ok for you right now, then you got your solution.
Also take a look on all other suggestions and improvements, this will let you code better, faster and more intuitive in your future → less problems + faster and more efficient coding.

AND DO NOT FORGET → YOU NORMALY DO NOT NEED ALL THAT BIG CODE IN FRONTEND.

const key = "...............";

Another thing → is the API-KEY, which you are storing directly inside of your BACKEND!
Yes, backend is more secure → but still not good enough. You better store your key inside of Wix-Secrets and you implement the Wix-Secret-API aswell into your backend.

Yes, thanks for the tips. I will of course look at the other suggestions again to improve the code.

I already have Wix Secrets on my to-do list :innocent:
The API key only works with my domain, so that’s at least another layer of security.

What I also realised is how helpful GPT can be if you use the right prompt. The development in this area is amazing.

1 Like