简体   繁体   中英

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.

You can't called the promise.reject method before you've returned the promise object up the chain. 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.

I thought that calling promise.reject before the 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...

   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:

 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

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

You can only reject or resolve the promise using the dfd object. The promise does not allow you to do that.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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