返回一个承诺抛出错误的 Promise [英] Return a Promise that promises to throw error
问题描述
我对使用 Promise 还很陌生,我主要坚持使用直接回调.下面的代码碰巧在 Angular Service 中找到,但这并不重要,主要是关于如何创建一个承诺会抛出某个错误的承诺.所以这就是合并回调时会发生的情况,从而避免了这个问题:
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'));
}
}
...但是将上面的内容改为使用纯 Promises,我不知道该怎么做:
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.
推荐答案
您可以注入 $q
服务并返回 $q.reject(reason)
,例如:
You could inject $q
service and return $q.reject(reason)
, e.g:
return $q.reject('NO_INDEX');
来自$q 文档:
创建一个因指定原因被拒绝的承诺.
Creates a promise that is resolved as rejected with the specified reason.
这篇关于返回一个承诺抛出错误的 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!