I am relatively new to utilizing promises, as I typically rely on traditional callbacks. The code snippet below is from an Angular Service, but the framework doesn't play a significant role in this context. What really matters is how to generate a promise that guarantees to throw a specific error. Here is how it would look with callbacks to handle this situation:
var client = algolia.Client('ApplicationID', 'apiKey');
var indices = {
users: client.initIndex('users'),
topics: client.initIndex('topics')
}
return {
search: function(indexName, searchTerms, cb){
var index = indices[indexName];
if(index){
index.search(searchTerms).then(function handleSuccess(msg){
cb(null,msg);
}, function handleError(err){
cb(err);
}
}
else{
cb(new Error('no matching index'));
}
}
...but when trying to convert the above to solely use Promises, I find myself unsure of the approach:
var client = algolia.Client('ApplicationID', 'apiKey');
var indices = {
users: client.initIndex('users'),
topics: client.initIndex('topics')
}
return {
search: function(indexName, searchTerms){
var index = indices[indexName];
if(index){
return index.search(searchTerms); //returns a promise
}
else{
//how can I create a promise that will result in throwing an error when there's no matching index?
}
}
Although there are various ways to restructure the code to tackle this issue, I am interested in exploring a direct solution.