问题
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.
回答1:
You could inject $q
service and return $q.reject(reason)
, e.g:
return $q.reject('NO_INDEX');
From $q documentation:
Creates a promise that is resolved as rejected with the specified reason.
回答2:
You just need to return a rejected promise with $q.reject(err)
:
return {
search: function(indexName, searchTerms){
var index = indices[indexName];
if(index){
return index.search(searchTerms); //returns a promise
}
else{
// return rejected promise if no match
return $q.reject(new Error("no matching index"));
}
}
Documentation here.
来源:https://stackoverflow.com/questions/33292312/return-a-promise-that-promises-to-throw-error