微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 检查对象是否是一个有前途的功能

在protractor.js中,

我有承诺/推迟的功能.例如

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

我可以使用什么类型的typeof语句组合来检查这个东西(当传递给别的东西时)是否有承诺?

> typeof promiseMaybe ===’function’
> typeof promiseMaybe.then ===’function’

>&&’ed with prior?

或者是否有像…这样的非类型函数

> promiseMaybe.isThenable
> protractor.promise.isThenable(promiseMaybe)

澄清

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

解决方法:

Protractor中有一个辅助方法 – 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,here you can find the source code of the method获取方法

/**
 * 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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐