I am fairly new to using promises, I mostly stick to straight up callbacks. The following code happens to be found in an Angular Service, but that doesn't really matter that much, it's mostly regards how to create a promise that will promise to throw a certain error. So this is how it would happen with callbacks being incorporated, which avoids the problem:
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 changing the above to use pure Promises, I don't know what to do exactly:
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{
//if there is no matching index, how can I return a promise then will return an error?
}
}
I know there are different ways to structure the code to avoid the problem at hand but I am curious if there is way to solve it directly.