How can I call an async function in another controller? πŸ€”

Hello Guys,

I have a ContentType A whose controller looks like this:

module.exports = {
...
const res = await filterObject(obj);
...
};

async function filterObject(obj) {
...
}

My question is how can i use the asynchronous function filterObject(obj) in another controller B? :thinking:

Thanks in advance!

Hello @mingxi ,

For this use case I would say that it depends on what the filterObject(obj) function is doing. If its content is strongly related to the business context you are within (API, plugin, …), I would recommend to expose it has part of a of service. So you can call it from anywhere using thee proper syntax.

On the other part, if the business logic of the function is not bound to your context. I would export it has a function in the config/functions directory.

I don’t know if this is the recommended way for handling this, but it works for me.

Hope that helps.

2 Likes

Hello @kevin_coulibaly ,

thank you very much for the tips, I have placed it as a service function. It works just fine.

In Service of ContentType A

module.exports = {
...
async filterObject(obj) {
...
}
...
};

Calling in Controller of ContentType X:

let res = await strapi.services.a.filterObject(obj);

I still have to find out how to use it in β€œconfig/functions” but for the first time the problem is solved. :+1:

Best regards! :beer: