检查对象是否有前途的功能 [英] Checking if an object is a promising function

查看:70
本文介绍了检查对象是否有前途的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有应允/递延的功能.例如

I have functions that promise/defer. For example

var myFunc = function(_params) {
  var deferred = protractor.promise.defer();
  /***do magical code things****/
  /***wait for other promises***/
  /*****deferred.fulfill();*****/
  return deferred.promise;
};

我可以使用哪种类型的typeof语句组合来检查此事物(传递给其他事物时)是否可以保证?

What sort of combinations of typeof statements can I use to check if this thing (when passed to something else) promises?

  • typeof promiseMaybe === 'function'
  • typeof promiseMaybe.then === 'function'
    • &&与先前有联系吗?
    • typeof promiseMaybe === 'function'
    • typeof promiseMaybe.then === 'function'
      • &&'ed with prior?

      或者是否有非typeof函数,例如...

      Or is there a non-typeof function like...

      • promiseMaybe.isThenable
      • protractor.promise.isThenable(promiseMaybe)
      • promiseMaybe.isThenable
      • protractor.promise.isThenable(promiseMaybe)

      我有一个方法可以接收myFunc作为参数,但是该方法也可以接收字符串和查找器.我需要知道如何在调用函数之前就知道参数是否为承诺了某些功能的函数.

      I have a method that will receive myFunc as a parameter, but this method can also receive strings and finders. I need to know how to tell if a parameter is the function that promises something, possibly before calling the function.

      推荐答案

      在Protractor中有一个用于此目的的辅助方法-protractor.promise.isPromise():

      There is a helper method in Protractor for that - protractor.promise.isPromise():

      var el = element(by.css('foo'));
      
      protractor.promise.isPromise('foo'); // false
      protractor.promise.isPromise(el); // false
      protractor.promise.isPromise(el.click()); // true
      

      量角器直接从selenium-webdriver在这里您可以找到该方法的源代码:

      /**
       * Determines whether a {@code value} should be treated as a promise.
       * Any object whose "then" property is a function will be considered a promise.
       *
       * @param {*} value The value to test.
       * @return {boolean} Whether the value is a promise.
       */
      promise.isPromise = function(value) {
        return !!value && goog.isObject(value) &&
            // Use array notation so the Closure compiler does not obfuscate away our
            // contract. Use typeof rather than goog.isFunction because
            // goog.isFunction accepts instanceof Function, which the promise spec
            // does not.
            typeof value['then'] === 'function';
      };
      

      因此,基本上,任何使用then方法的对象都被视为Promise.

      So basically, any object with a then method is considered a Promise.

      这篇关于检查对象是否有前途的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆