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 anError
object. More info on the error can be found inerror.message
.content
: the JavaScript object containing the response from the server.
Copy
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.
Copy
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.
Copy
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.