return an empty array from backend

I am having a backend function as follow:

export async function getTarif(saison_id, typeChalet, memberType, famille) {
    
let periodTarif = new Array();
    
    ...
    
    let gtTarf = await wixData.query("tarif")
    ... .find()
        .then(async (results) => {
            let rowTarifCount = results.totalCount;
            if (rowTarifCount > 0) {
                let rowTarif = results.items;
                let index = 0;

                for (let index = 0; index < rowTarif.length; index++) {
...
                    let tabl = {
                        "period": element._id,
                        "prixDay": element.prixDay,
                        "prixHebdo": element.prixHebdo,
                        "prixMensuel": element.prixMensuel 
                    }
                    periodTarif[index] = tabl;
                };
                console.log('"getTarif: periodTarifperiodTarifperiodTarif => \n' + JSON.stringify(periodTarif));
            }
        })
        .catch((err) => {
            console.log("get tarif is ERROR " + err);
            console.error(err);
        })
    setTimeout(() => {

    //    return periodTarif;

    }, timeout);

     return periodTarif;
}

even if periodTarif is having data, the function always return an empty array. If I used a setTimeout, it return undefined.

What should I do to return my array’s data?

You should delete the await from your query. You are using a .then() so the await is an error. And therefore, you don’t need async in the function definition.

You need to return your results inside of the query’s .then() function. And, you also need to return the result of the Promise’s then().

To add each item to the array, you should use the array’s push() function .

You want something like this (not tested):

export function getTarif(saison_id, typeChalet, memberType, famille) {

  return wixData.query("tarif")
    .find()
    .then(async (results) => {
      let rowTarifCount = results.totalCount;
      if (rowTarifCount > 0) {
        let rowTarif = results.items;
        let index = 0;

        let periodTarif = new Array();
        for (let index = 0; index < rowTarif.length; index++) {

          let tabl = {
            "period": element._id,
            "prixDay": element.prixDay,
            "prixHebdo": element.prixHebdo,
            "prixMensuel": element.prixMensuel
          }
          periodTarif.push(tabl);
        };
        console.log('"getTarif: periodTarifperiodTarifperiodTarif => \n' + JSON.stringify(periodTarif));
        return periodTarif;
      }
    })
    .catch((err) => {
      console.log("get tarif is ERROR " + err);
      console.error(err);
    })
}

See the section Returning in a .then() in the article Working with Promises.

See the article Promises, Promises for a further explanation on Promises.

Big thanks for the advise @yisrael-wix . I transformed all the promise call as suggested. It seems to work well in the backend. All object in return has data.

But I always receive undefined while calling it from the frontend. So I converted the frontend call in the backend to see the result. I am receiving a message from the Wix editor that the function is a type void. Here the message received from the converted backend function:

See the getTarifReserv function. Is it right to say this is because of the void function I am receiving an undefined

export function getTarifReserv(user) {
       return wixData.query("myParams")
        .eq("title", "Reservation")
        .eq("userId", user._id)
        .find()
        .then((results) => {
            let rowParam = results.items[0];
            if (rowParam !== null && rowParam !== undefined) {
                return {
                    "total": rowParam.cout,
                    "period": rowParam.period
                };
           } else {
                let err = "getTarifReserv: 2 ERREUR Logique, pas de record MyParams pour Reservation pour userID = " + user._id;
                console.error(err);
                return {
                    "total": 0,
                    "period": []
                };
            }
        })
        .catch((err) => {
            console.error(err);
        })
}

Can you help for that part too. to resolve the undefined problem. Here is the front end function:

export function calculTarif(selChalet, selFrom, selTo, selMbr, selGroup, selFamille, member) {
    let dollar = 0;
    return estimeTarif(selChalet, selFrom, selTo, selMbr, selGroup, selFamille, member)
        .then((tarif) => {
            let total = 0;
            return tarif;
        })
        .then(tarif => {
            //let calcDollar = 
            return getTarifReserv(member)
                .then(response => {
                    dollar = selTarif = cout = response.cout;
                    periodTarif = response.period;

                    if (dollar === 0) {
                        $w('#tarif').text = $w('#adminTarif').text = "?";
                    } else {
                        let tmp = cout.toLocaleString();
                        $w('#adminTarif').text = $w('#tarif').text = tmp;
                    }
                    return response;
                })
        })
        .catch((err) => {
            console.error(err);
        });
}

You will need to add some console.log() debug statements to better understand what’s happening.

I would suggest that it’s better to see if you have results by checking the length of the returned items:

Instead of this:

.then((results) => {
   let rowParam = results.items[0];

If there are no items, you will end up with an undefined runtime error.

You want something like this (not tested):

.then((results) => {
    if(results.items.length > 0) {
        // do stuff with the results
        let rowParam = results.items[0];
        return{
            "total": rowParam.cout,
            "period": rowParam.period
        };
    }
    else {
       return{
            "total": 0,
            "period": []
        };
    }

@yisrael-wix :
I am having a scenario where I am not sure how I would chain all the then Promise call: and all the parameter that need to be passed till the last level of chain call.

How would you rewrite the promiseCall

export function ABC(p1, p2, p3, p4) {
I need to convert p1 and p2.
d1 = promiseCallD(p1);
d2 = promiseCallD(p2);
let isActive = true;

while (isActive) {
    wixData.query("collection")
     .eq("d1", d1)
     .lt("d2"), d2)
     .find()
     .then (results => {
       row = results.items[0];
       ...
       return  {"data":row.data,
               "d1": d1,
               "d2": d2
              }; 
       })
      .then (res => {
        let tmp = null
        f1 = PromiseCallF(p3, res.d1);
        f2 = PromiseCallF(p4, res.d2);
        row = {"f1": f1,
               "f2": f2,
               "d1": d1,
               "d2": d2
               };
        return tbl.push(row); =        
       })
     }
  return  data
  }     

Saying that a Promise call should be code like that:

return PromiseCallD(a) {
  .then(result => {
  ...
    return data;
    })
  }