API Reference / API Methods / Promises, callbacks & errors
Aug. 06, 2019

Promises, callbacks & errors

Callbacks

Every API call takes a callback as the last parameter. This callback is then called with two arguments:

  • error: null or an Error object. More info on the error can be found in error.message.
  • content: the JavaScript object containing the response from the server.
1
2
3
4
5
6
7
8
9
10
11
12
13
const algoliasearch = require('algoliasearch');
const client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
const index = client.initIndex('instant_search');

index.search({ query: 'query string' }, (err, { hits } = {}) => {
  if (err) {
    console.log(err);
    console.log(err.debugData);
    return;
  }

  console.log(hits);
});

Promises

If you don’t provide a callback, you get a promise (but never both).

We use jakearchibald/es6-promise as a polyfill when necessary.

1
2
3
4
5
6
7
index.search({ query: 'query string' })
  .then(({ hits } = {}) => {
    console.log(hits);
  }).catch(err => {
    console.log(err);
    console.log(err.debugData);
  });

Async/Await

You can also use the async/await syntax to handle promises.

1
2
3
4
5
6
7
8
9
(async () => {
  try {
    const content = await index.search({ query: 'query string' });
    console.log(content);
  } catch (err) {
    console.log(err);
    console.log(err.debugData);
  }
})();

Error Handling

The client sends errors when a method call fails. You can get detailed debugging information in err.debugData, which contains the array of requests parameters that were used to issue requests.

Did you find this page helpful?

JavaScript