返回承诺抛出错误承诺 [英] Return a Promise that promises to throw error
问题描述
我是相当新的使用的承诺,我主要是坚持直线上升回调。下面code发生在一个角服务被发现,但没有真正的问题那么多,它主要是关于如何创建一个承诺,承诺将抛出一定的误差。因此,这是它如何与回调发生被纳入,避免了问题:
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'));
}
}
...但改变上述用纯承诺,我不知道该怎么做确切:
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?
}
}
我知道有很多不同的方法来构造code,以避免在手头的问题,但我很好奇,如果有办法直接解决这个问题。
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.
推荐答案
您可以注入 $ Q
服务,并返回 $ q.reject(原因)
,例如:
You could inject $q
service and return $q.reject(reason)
, e.g:
return $q.reject('NO_INDEX');
创建与指定的理由拒绝了解决的承诺。
Creates a promise that is resolved as rejected with the specified reason.
这篇关于返回承诺抛出错误承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!