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
  • 2
    `.then(console.log('getFamilies then'))` -> `.then(() => console.log('getFamilies then'))` – VLAZ Feb 01 '21 at 18:13
  • You're *immediately* calling `console.log` and assing its return value as the `then` function. – Quentin Feb 01 '21 at 18:15
  • 2
    IN additon to the above, you're never awaiting the recursive call to `getFamilies` – Jamiec Feb 01 '21 at 18:15
  • 3
    The inner `getFamilies(enfant.id)` needs to be returned in a `Promise.all` for the outer `.then` to wait for it to finish – CertainPerformance Feb 01 '21 at 18:16
  • 1
    Also, what is `famillesReliees`? If it's a global array you're sooner or later going to run into the problems associated with trying to return a value from an async function – Jamiec Feb 01 '21 at 18:17
  • Thank you, what do you suggest then for `famillesReliees` – ermat77 Feb 01 '21 at 18:38

1 Answers1

1

This isn't doing what you think:

getFamilies(2).then(console.log('getFamilies then'))

This executes console.log immediately and passes its result (which is undefined) as the function to be executed after the getFamilies operation.

Wrap the console.log operation in a function to be executed later:

getFamilies(2).then(() => console.log('getFamilies then'))

Structurally, this is just like your use of .then() in the getFamilies function above. The only differences are:

  • There are no parameters/arguments for the function, so just use () instead of a variable name. (Your callback function above has a parameter called res.)
  • There's only one line in the function, so the curly braces {} aren't needed. (Technically this also returns the result of that line, but in this case the returned result is undefined and nothing uses it so no harm done.)
David
  • 208,112
  • 36
  • 198
  • 279