Router entries from DB

I have a router on my site, and I want to build its site map entries based on items from my DB collection.
The way I found for doing that is using wixData.query, then using map() on the results, and building a the site map entry there.
The problem is that because wixData.query() is a asyncronous function, the _SiteMap() function ends before the wixData.query() does. Now, I can try to make the code wait for it to finish (not sure how to do it, but I guess I can find out), but seeing as _SiteMap() doesn’t just run once - that would really slow the site down.

So, any other ideas for implementing this that don’t involve querying the database too often?

Hello Tal,

Note that you can return a promise from the sitemap function.
You can make this promise resolve only after the wixData query and all mappings of its results are finished.
Meaning in general, that whatever is calling your sitemap function will “wait” for the the final data.

As wixData.query already returns a promise, you can just chain it with additional modifications and return the final result.
It may look something like this:

function itemToSitemapEntry (item) {
    // return the item as a sitemap entry
}

export function myRouter_SiteMap(sitemapRequest) {
    return wixData.query("myCollection")
        .find()
        .then((results) => results.items.map(itemToSitemapEntry))
}

Good luck!