Index Operations Are Asynchronous
All indexing methods are asynchronous. What you’re doing when calling these methods is adding a new job to a queue: it is this job, and not the method, that performs the desired action.
In most cases, the job is executed within seconds, if not milliseconds. Yet, it all depends on what is in the queue. When the queue has many pending tasks, the new job needs to wait its turn.
When to Wait for Tasks
To help manage this asynchronicity, each method returns a unique
taskId which you can use with the waitTask method. Using this method guarantees that a job has finished before proceeding with a new request. There are a few situations when this comes in handy.
You want to use waitTask to manage dependencies, for example, when deleting an index before creating a new index with the same name or clearing an index before adding new objects.
Atomic reindexing is a way to update all your records without any downtime, by populating a temporary index and replacing the destination index with it. You don’t need to implement this by yourself. Instead, you can use the replaceAllObjects method which does it all for you.
If you’re building a front-end interface that performs indexing operations, you may want to react to completed tasks. For example, you may want to display a success message when an indexing operation has completed, or refresh a page, or move on with some following, co-dependant operations, etc.
You also most often need waitTask in debugging scenarios, when you’re testing a search immediately after updating an index.
When Not to Wait for Tasks
In most scenarios, you don’t need to wait for tasks to complete before moving on with new ones. Using waitTask makes your indexing operations synchronous, thus slows them down.
Conversely, you don’t need to use waitTask in place of the asynchronous mechanisms of your programming language. You can ensure that tasks are queued in order by using promises or callbacks.