如何拒绝我没有创建的承诺?
问题描述:
相当新的承诺,在这里,我想知道..如何拒绝我没有创建的承诺?
考虑看看bluebird
包处理后的承诺:
- 创建解析器上的成功
- 解决/拒绝失败
- 返回创建的解析器
promise
属性
我一直在想如何才能ach即使使用已经创造承诺的软件包拒绝承诺提高catch
的效果也是如此,并且我只是使用它们的.then
链?
我的意思是,在我创建的解析器上使用reject
最终会向此函数的用户提出catch
。
如何提高catch
如果我没有解析器。链接承诺如下:
function doSomthing(): Promise<someValue>
return somePackage.someMethodWithPromise().then((result)=> {
return someValueToTheNextThen;
})
}
我已经看到了一些包实现这一目标是通过返回一个{ errors, result }
对象,以便在下一个then
可以检查是否有任何错误,并作出反应,但我想的唯一方法以提高catch
,而不是检查每一个then
我有..
希望我明确表示,请让我知道,如果有什么缺失。
在此先感谢您的帮助!
答
.then
也只是返回一个Promise。如果您确定存在错误,您可以简单地创建一个被拒绝的承诺并从那里返回。
return somePackage.someMethodWithPromise().then(result => {
if (result.erroneous()) return Promise.reject('erroneous data');
return someValueToTheNextThen;
})
您也可以从then
简单throw anError;
这也将在catch
块捕获。
答
就像在同步代码中一样,你可以通过抛出一个错误来实现。这是当你使用的承诺和已经是then
链里面做的事情成语:
function doSomething(): Promise<someValue>
return somePackage.someMethodWithPromise().then((result)=> {
if (badResult(result)) {
throw new Error('Bad result!');
}
return someValueToTheNextThen;
})
}
doSomething()
.then(result => {
// this will get skipped if an error was thrown
})
.catch(error => {
// error will be caught here if one was thrown
console.error(error);
});
+0
谢谢,生病了吧! –
感谢您的快速回复,看起来非常有前途;)生病给它一个镜头的明天,并尽快接受你的答案因为我看到这个工作:) –