[英]How do you reject a promise before calling any async code… (ex. reject upon detecting invalid arguments)
通常,您对异步代码使用promise ...,但是有时您需要在执行异步代码之前检查同步变量的状态。
在将promise对象返回到链上之前,无法调用promise.reject方法。 那么,通常如何处理呢?
function somePromiseFunction(opts) {
var promise = new Oath();
if( opts.requiredParam === undefined ) {
// How can I reject here?
// We haven't returned the promise to the calling function yet so we get an error
}
// async code here... when done it calls either promise.resolve or promise.reject
return promise.promise;
}
我正在为node.js使用誓言承诺库,但是我认为这几乎适用于任何情况。
我想打电话promise.reject
的前return promise.promise;
造成了问题。 原来,问题出在我的其余功能仍在执行中,这是导致异常的原因。
或者,可以包含else语句...
if( opts.requiredParam === undefined ) {
promise.reject("Missing required param");
return promise.promise; // <-- required otherwise the function will continue to execute
}
var x = opts.requiredParam.foo; // Would cause Uncaught exception otherwise
您可以抛出或只调用promise.reject
,而不做异步工作。
您可以拒绝“延迟”对象。
您没有说您使用的是什么库,但我假设使用jQuery:
var dfd = jQuery.Deferred();
// ....
dfd.reject(...)
如果您在延迟的对象上调用.promise()
,那么您将获得一个只读接口,并且无法使用该对象来解析/拒绝promise
var promise = dfd.promise(); // can't be used to reject or resolve
您只能使用dfd
对象拒绝或解决承诺。 promise
不允许您这样做。
function somePromiseFunction(opts) {
var promise = new Oath();
if( opts.requiredParam === undefined ) {
promise.reject("You suck");
}
// async code here... when done it calls either promise.resolve or promise.reject
return promise.promise;
}
您不需要返回拒绝它的诺言,在它返回之前,我将被拒绝,并且当函数返回时,仍然会在诺言上调用适当的回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.