0

I am trying to push in an array all the ids of objects that match my condition.

I am using a recursive function and I want to return a value when my recursive function has finished.

Here is my code :

const getFamilies = async function (family, famillesReliees) {
    await strapi.query('famille-de-materiel').findOne({ id: family })
        .then(res => {
            if (res.cats_enfant.length > 0) {
                res.cats_enfant.forEach(async enfant => {
                    famillesReliees = await getFamilies(enfant.id, famillesReliees)
                })
            } else {
                famillesReliees.push(res.id)
            }
        })
        return famillesReliees
}

async search() {
    let value = await getFamilies(2, [])
    return value
}

I don't understand why the "value" return before the end of the recursive function

ermat77
  • 23
  • 5
  • Why don't you use a `Promise` and do the recursion inside of it? When the recursion is done you can resolve it... It would be easy to manage. – ZeroWorks Feb 01 '21 at 20:14
  • what use does it have to overwrite `famillesReliees` in every step of the loop? Also the mix of then and await is not so good – Julian Kleine Feb 01 '21 at 20:23
  • 1. You're mixing `await` style and `.then()` style. You can't await something and also chain it a `.then()`, it doesn't make sense. 2. You are returning `famillesReliees` before the `.then()` happens. – Jeremy Thille Feb 01 '21 at 20:57

0 Answers0