perform.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * A simple perform command which allows access to the "api" in a callback.
  3. * Can be useful if you want to read variables set by other commands.
  4. *
  5. * ```
  6. * this.demoTest = function (browser) {
  7. * var elementValue;
  8. * browser
  9. * .getValue('.some-element', function(result) {
  10. * elementValue = result.value;
  11. * })
  12. * // other stuff going on ...
  13. *
  14. * // self-completing callback
  15. * .perform(function() {
  16. * console.log('elementValue', elementValue);
  17. * // without any defined parameters, perform
  18. * // completes immediately (synchronously)
  19. * })
  20. *
  21. * // asynchronous completion
  22. * .perform(function(done) {
  23. * console.log('elementValue', elementValue);
  24. * // potentially other async stuff going on
  25. * // on finished, call the done callback
  26. * done();
  27. * })
  28. *
  29. * // asynchronous completion including api (client)
  30. * .perform(function(client, done) {
  31. * console.log('elementValue', elementValue);
  32. * // similar to before, but now with client
  33. * // potentially other async stuff going on
  34. * // on finished, call the done callback
  35. * done();
  36. * });
  37. * };
  38. * ```
  39. *
  40. * @method perform
  41. * @param {function} callback The function to run as part of the queue. Its signature can have up to two parameters. No parameters: callback runs and perform completes immediately at the end of the execution of the callback. One parameter: allows for asynchronous execution within the callback providing a done callback function for completion as the first argument. Two parameters: allows for asynchronous execution with the "api" object passed in as the first argument, followed by the done callback.
  42. * @api commands
  43. */
  44. var util = require('util');
  45. var events = require('events');
  46. function Perform() {
  47. events.EventEmitter.call(this);
  48. }
  49. util.inherits(Perform, events.EventEmitter);
  50. Perform.prototype.command = function(callback) {
  51. var self = this;
  52. var doneCallback;
  53. if (callback.length === 0) {
  54. callback.call(self, self.client.api);
  55. doneCallback = function() {
  56. self.emit('complete');
  57. };
  58. } else {
  59. doneCallback = function() {
  60. var args = [function() {
  61. self.emit('complete');
  62. }];
  63. if (callback.length > 1) {
  64. args.unshift(self.client.api);
  65. }
  66. callback.apply(self, args);
  67. };
  68. }
  69. process.nextTick(doneCallback);
  70. return this;
  71. };
  72. module.exports = Perform;