How can I make the game not wait for a function to finish?

Yo! I just added pathfinding into my 2D game, which works just fine if there’s a path. But if there isn’t a valid path, the AI has to check every single node in the grid I’ve created, which results in a noticeable pause before it outputs an error.
In most other games I’ve seen, instead of freezing the whole game, an AI would just stop moving until it finds a solution while the game runs around it. Is there any way I can do that? A [system.realtime] or something I can add to my function? Or maybe something with coroutines?

The keyword here is threading. You can create new threads pretty easily - the more interesting topic is how to integrate the results into the main thread.
I once wrote a little class for this: Small classes that allow for comfortably executing a single thread or a threadpool task in a coroutine. · GitHub

You can use it like this:

yield return new CoroutineThread(DoSomething);

in a coroutine. Whatever comes after this line is executed once the thread is finished.