简体   繁体   English

如何在调用任何异步代码之前拒绝承诺(例如,在检测到无效参数时拒绝)

[英]How do you reject a promise before calling any async code… (ex. reject upon detecting invalid arguments)

Generally, you use promises for async code... but sometimes you need to check the status of variables which is synchronous before executing the async code. 通常,您对异步代码使用promise ...,但是有时您需要在执行异步代码之前检查同步变量的状态。

You can't called the promise.reject method before you've returned the promise object up the chain. 在将promise对象返回到链上之前,无法调用promise.reject方法。 So, what's the way this is typically handled? 那么,通常如何处理呢?

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;
}

I am using the oath promise library for node.js, but I think this would apply to pretty much any. 我正在为node.js使用誓言承诺库,但是我认为这几乎适用于任何情况。

I thought that calling promise.reject before the return promise.promise; 我想打电话promise.reject的前return promise.promise; was causing the issue. 造成了问题。 Turns out, the issue was the rest of my function was still executing which is what was causing the exception. 原来,问题出在我的其余功能仍在执行中,这是导致异常的原因。

Alternatively, could of included an else statement... 或者,可以包含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 ,而不做异步工作。

You can reject a "Deferred" object. 您可以拒绝“延迟”对象。

You don't say what library you're using but I'll assume jQuery: 您没有说您使用的是什么库,但我假设使用jQuery:

 var dfd = jQuery.Deferred();

 // ....

 dfd.reject(...)

If you called .promise() on your deferred object then you will get a read-only interface and you can't resolve/reject the promise using that object 如果您在延迟的对象上调用.promise() ,那么您将获得一个只读接口,并且无法使用该对象来解析/拒绝promise

var promise = dfd.promise(); // can't be used to reject or resolve

You can only reject or resolve the promise using the dfd object. 您只能使用dfd对象拒绝或解决承诺。 The promise does not allow you to do that. 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;
}

You don't need to return the promise for rejecting it, I will be rejected before it's returned and the proper callbacks still be called on the promise when the function returns. 您不需要返回拒绝它的诺言,在它返回之前,我将被拒绝,并且当函数返回时,仍然会在诺言上调用适当的回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM