Way to find if function will return promise

后端 未结 3 1360
花落未央
花落未央 2020-12-20 01:34

Below I have a function that returns a promise that resolves true. Is there any way I can find out if a function will return a promise?

var myPr         


        
相关标签:
3条回答
  • 2020-12-20 01:59

    Is there any way I can find out if a function will return a promise?

    No (not without actually invoking it). Your best recourse here is to rely on consistency in naming and API conventions.

    Just for a quick "proof" on the inability to test for a return type, consider the following function:

    function maybeAPromise() {
        if (Math.random() < .5) {
            return Promise.resolve('foo');
        } else {
            return 'bar';
        }
    }
    

    While I personally feel that the productivity advantages of dynamic languages like JavaScript are worth their tradeoffs, there's no denying that the lack of compile-time type safety is one of the tradeoffs in the "negative" category.

    That being said, Promise.resolve() is handy if you simply want to force a result to be a Promise. E.g.,

    Promise.resolve(maybeAPromise()).then(...);
    
    0 讨论(0)
  • 2020-12-20 02:06

    Check the return value after you call it. This is JavaScript after all, not some statically typed language. You have all the same options:

    function foo(func) {
      var result = func();
      if (result instanceof Promise) {
        result.then(bar).catch(failure);
      } else {
        bar(result);
      }
    }
    
    foo(myPromiseFunction);
    foo(mySyncFunction);
    

    But I recommend against such optimizations, as it increases complexity. Better to let Promise.resolve() do its thing and fold your synchronous code flow into your asynchronous one. .then does this automatically for you to anything you return, so I find this approach quite readable.

    0 讨论(0)
  • 2020-12-20 02:07

    There is no good way to do this, but you can call the methods and inspect their return values.

    function willReturnPromise(fn) {
        const result = fn();
        return result && typeof result.then === 'function';
    }
    

    The A+ Promise spec does not require promises to have anything other than a function named then, so this is the best you can do if you want the function to work with all Promise implementations.

    Calling the function and throwing away the result just to determine this is not a good idea though.

    0 讨论(0)
提交回复
热议问题