Home > Software design >  Nodejs Execute after a recursive function is done
Nodejs Execute after a recursive function is done

Time:09-17

I have a controller that basically performs a recursive call to retrieve how categories and their deleted items, but a "category_item" has a property called "next_steps" which is an array of categories, so I need to retrieve those categories and their items as well.

So I made a recursive function, it works, but I need to run something else when it actually ends, how can I do that? here's my code:

const recoveryCategory = async (req, res) => {
    try {
        const categoryId = req.params.categoryId
        const category = await nmCategorySvcV2.getByIdDeleted(categoryId)

        if (category === null){
            throw new Error("This category is not deleted.")
        }

        __recoveryRecursive(categoryId)
        // run something after 


        res.json({ success: true, message: "Success." })
    } catch (err){
        res.json({ success: false, message: err.message })
    }
}

const __recoveryRecursive = async (categoryId) => {
    const category = await nmCategorySvcV2.getByIdDeleted(categoryId)
    if (category === null){
        return
    }

    await nmCategorySvcV2.update(categoryId, { deleted: false })

    const categoryItens = await categoryItemSvcV2.getAllItensByCategory(categoryId)

    for (let i = 0; i < categoryItens.length; i  ) {
        const categoryItem = categoryItens[i]

        if (categoryItem.deleted == true) {
            const item = await itemSvcV2.getByIdNoPopulate(categoryItem.item, categoryItem.page)

            if (item.deleted == true) {
                itemSvcV2.update(item._id, { deleted: false })
                categoryItemSvcV2.updateItensProp(item._id, { deleted: false })
            }

            const itemPrice = await itemPriceSvcV2.getById(categoryItem.price)

            if (itemPrice.deleted == true) {
                itemPriceSvcV2.updateObject({ _id: itemPrice._id }, { deleted: false })
            }

            categoryItemSvcV2.update(categoryItem._id, { deleted: false })

            if (categoryItem.next_steps.length > 0){
                for (let j = 0; j < categoryItem.next_steps.length; j  ){
                    const categryNextStep = categoryItem.next_steps[j].category
                    __recoveryRecursive(categryNextStep)
                }
            }
        }
    }
}

CodePudding user response:

Just add await before the recursive call because it returns a promise wich must be handled .

  • Related