> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Wait for operations

> Wait for a task to complete to ensure synchronized index updates.

export const Legacy = ({title, href}) => {
  return <Note>

    This page documents an earlier version of the API client.
    For the latest version, see <a href={href}>{title}</a>.

    </Note>;
};

<Legacy title="Wait for task" href="/doc/libraries/sdk/methods/search/wait-for-task" />

**Required ACL:** `addObject`

All Algolia write operations are asynchronous.
When you make a request for a write operation, for example, to add or update records in your index, Algolia creates a task on a queue and returns a `taskID`.
The task itself runs separately, depending on the server load.
You can wait for a write operation to complete by using the task's `taskID` and the `waitTask` method.

## Examples

### Wait until a new object is added to an index

<CodeGroup>
  ```cs C# theme={"system"}
  Contact contact = new Contact
  {
    Firstname = "Jimmie",
    Lastname = "Barninger"
  };

  index.SaveObject(contact, autoGenerateObjectId: true).Wait();

  // Asynchronous
  var resp = await index.SaveObjectsAsync(contacts, autoGenerateObjectId: true);
  resp.Wait();
  ```

  ```go Go theme={"system"}
  type Contact struct {
  	Firstname string `json:"firstname"`
  	Lastname  string `json:"lastname"`
  }

  contact := Contact{
  	Firstname: "Jimmie",
  	Lastname:  "Barninger",
  }

  res, err := index.SaveObject(contact, opt.AutoGenerateObjectIDIfNotExist(true))
  err = res.Wait()
  ```

  ```java Java theme={"system"}
  BatchIndexingResponse resp = index.saveObject(
    new Contact().setFirstname("Jimmie").setLastname("Barninger")
  );

  // All objects implementing the AlgoliaWaitableResponse interface
  // Can be awaited with the .waitTask() method
  resp.waitTask();
  ```

  ```js JavaScript theme={"system"}
  const object = {
    firstname: "Jimmie",
    lastname: "Barninger",
  };

  index
    .saveObject(object, { autoGenerateObjectIDIfNotExist: true })
    .wait()
    .then(({ objectID }) => {
      console.log(objectID);
    });
  ```

  ```kotlin Kotlin theme={"system"}
  val json = json {
      "Firstname" to "Jimmie"
      "Lastname" to "Barninger"
  }

  index.apply {
      saveObject(json).wait()
  }
  ```

  ```php PHP theme={"system"}
  $index->addObject(
    [
      'firstname' => 'Jimmie',
      'lastname'  => 'Barninger'
    ]
  )->wait();
  ```

  ```python Python theme={"system"}
    index.save_object(
        {"firstname": "Jimmie", "lastname": "Barninger"},
        {"autoGenerateObjectIDIfNotExist": True},
    ).wait()
  ```

  ```ruby Ruby theme={"system"}
  # Asynchronous call and wait until complete
  response = index.add_object({firstname: "Jimmie", lastname: "Barninger"})
  response.wait

  # Synchronous call, that handles the wait internally
  index.add_object!({firstname: "Jimmie", lastname: "Barninger"})
  ```

  ```scala Scala theme={"system"}
  for {
    t <- client.execute { index into "toto" `object` MyObject("test") }
    r <- client.execute { waitFor task t from "toto" }
  } yield "indexing is done"
  ```

  ```swift Swift theme={"system"}
  struct Contact: Codable {
    let firstName: String
    let lastName: String
  }

  let object = Contact(firstName: "Jimmie",
                       lastName: "Barninger")

  try index.saveObject(object, autoGeneratingObjectID: true) { result in
      if case .success(let waitableWrapper) = result {
        waitableWrapper.wait() { result in
          if case .success(let response) = result {
            print("New object is indexed")
          }
        }
      }
  }
  ```
</CodeGroup>

If you want to ensure multiple objects have been indexed, you must check all `taskID`s.

### Wait for indexing of a new object and send extra HTTP header

<CodeGroup>
  ```cs C# theme={"system"}
  List<Contact> contacts = new List<Contact>
  {
      new Contact
      {
        ObjectID = "myID1",
        Firstname = "Jimmie",
        Lastname = "Barninger"
      },
      new Contact
      {
        ObjectID = "myID2",
        Firstname = "Warren",
        Lastname = "Speach"
      }
  };

  RequestOptions requestOptions = new RequestOptions
  {
      Headers = new Dictionary<string,string>{ { "X-Algolia-User-ID", "user123" } }
  };

  index.SaveObjects(contacts, requestOptions).Wait();

  // Asynchronous
  var resp = await index.SaveObjectsAsync(contacts, requestOptions);
  resp.Wait();
  ```

  ```go Go theme={"system"}
  type Contact struct {
  	Firstname string `json:"firstname"`
  	Lastname  string `json:"lastname"`
  }

  contact := Contact{
  	Firstname: "Jimmie",
  	Lastname:  "Barninger",
  }

  opts := []interface{}{
  	opt.AutoGenerateObjectIDIfNotExist(true),
  	opt.ExtraHeaders(map[string]string{"X-Algolia-User-ID": "userID2"}),
  }

  res, err := index.SaveObject(contact, opts...)
  err = res.Wait()
  ```

  ```java Java theme={"system"}
  BatchIndexingResponse resp = index.saveObject(
    new Contact().setFirstname("Jimmie").setLastname("Barninger"),
    new RequestOptions().addExtraHeader("X-Algolia-User-ID", "user123")
  );

  // All objects implementing the AlgoliaWaitableResponse interface
  // Can be awaited with the .waitTask() method
  resp.waitTask();
  ```

  ```js JavaScript theme={"system"}
  const object = {
    firstname: "Jimmie",
    lastname: "Barninger",
  };

  const waitRequestOptions = {
    headers: {
      "X-Forwarded-For": "94.228.178.246",
    },
  };

  index
    .saveObject(object, { autoGenerateObjectIDIfNotExist: true })
    .wait(waitRequestOptions)
    .then(({ objectID }) => {
      console.log(objectID);
    });
  ```

  ```php PHP theme={"system"}
  $index->addObject(
    [
      'firstname' => 'Jimmie',
      'lastname'  => 'Barninger'
    ]
  )->wait([
    'X-Forwarded-For' => '94.228.178.246'
  ]);
  ```

  ```python Python theme={"system"}
  index.save_object(
      {"firstname": "Jimmie", "lastname": "Barninger"},
      {"autoGenerateObjectIDIfNotExist": True},
  ).wait({"X-Forwarded-For": "94.228.178.246"})
  ```

  ```ruby Ruby theme={"system"}
  extra_headers = {
    :"X-Algolia-User-ID" => "user123"
  }

  time_before_retry = 100

  index.wait_task(res["taskID"], time_before_retry, extra_headers)
  ```

  ```scala Scala theme={"system"}
  for {
    t <- client.execute { index into "toto" `object` MyObject("test") }
    r <- client.execute {
      waitFor task t from "toto" options RequestOptions(
        extraHeaders = Some(Map("X-Algolia-User-ID" => "user123"))
      )
    }
  } yield "indexing is done"
  ```

  ```swift Swift theme={"system"}
  struct Contact: Codable {
    let firstName: String
    let lastName: String
  }

  let object = Contact(firstName: "Jimmie",
                       lastName: "Barninger")

  var requestOptions = RequestOptions()
  requestOptions.headers = ["X-Algolia-User-ID": "user123"]

  try index.saveObject(object, autoGeneratingObjectID: true) { result in
      if case .success(let waitableWrapper) = result {
        waitableWrapper.wait(requestOptions: requestOptions) { result in
          if case .success(let response) = result {
            print("New object is indexed")
          }
        }
      }
  }
  ```
</CodeGroup>

## Parameters

<ParamField body="taskID" type="string" required>
  Task ID of the indexing task to wait for.
</ParamField>

<ParamField body="requestOptions" type="list">
  A list of request options to send along with the query.
</ParamField>
