d1481f5e8b5e35beabd1f790b9935fdd1ed9244709b13330fe2870d9ac2c41cf0c4db7760c4a5ddf5b97027cbd39452062530221f8ff83c7a08815524a3047 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /* @prettier */
  2. import { Observable } from '../Observable';
  3. import { SchedulerLike } from '../types';
  4. import { bindCallbackInternals } from './bindCallbackInternals';
  5. export function bindNodeCallback(
  6. callbackFunc: (...args: any[]) => void,
  7. resultSelector: (...args: any[]) => any,
  8. scheduler?: SchedulerLike
  9. ): (...args: any[]) => Observable<any>;
  10. // args is the arguments array and we push the callback on the rest tuple since the rest parameter must be last (only item) in a parameter list
  11. export function bindNodeCallback<A extends readonly unknown[], R extends readonly unknown[]>(
  12. callbackFunc: (...args: [...A, (err: any, ...res: R) => void]) => void,
  13. schedulerLike?: SchedulerLike
  14. ): (...arg: A) => Observable<R extends [] ? void : R extends [any] ? R[0] : R>;
  15. /**
  16. * Converts a Node.js-style callback API to a function that returns an
  17. * Observable.
  18. *
  19. * <span class="informal">It's just like {@link bindCallback}, but the
  20. * callback is expected to be of type `callback(error, result)`.</span>
  21. *
  22. * `bindNodeCallback` is not an operator because its input and output are not
  23. * Observables. The input is a function `func` with some parameters, but the
  24. * last parameter must be a callback function that `func` calls when it is
  25. * done. The callback function is expected to follow Node.js conventions,
  26. * where the first argument to the callback is an error object, signaling
  27. * whether call was successful. If that object is passed to callback, it means
  28. * something went wrong.
  29. *
  30. * The output of `bindNodeCallback` is a function that takes the same
  31. * parameters as `func`, except the last one (the callback). When the output
  32. * function is called with arguments, it will return an Observable.
  33. * If `func` calls its callback with error parameter present, Observable will
  34. * error with that value as well. If error parameter is not passed, Observable will emit
  35. * second parameter. If there are more parameters (third and so on),
  36. * Observable will emit an array with all arguments, except first error argument.
  37. *
  38. * Note that `func` will not be called at the same time output function is,
  39. * but rather whenever resulting Observable is subscribed. By default call to
  40. * `func` will happen synchronously after subscription, but that can be changed
  41. * with proper `scheduler` provided as optional third parameter. {@link SchedulerLike}
  42. * can also control when values from callback will be emitted by Observable.
  43. * To find out more, check out documentation for {@link bindCallback}, where
  44. * {@link SchedulerLike} works exactly the same.
  45. *
  46. * As in {@link bindCallback}, context (`this` property) of input function will be set to context
  47. * of returned function, when it is called.
  48. *
  49. * After Observable emits value, it will complete immediately. This means
  50. * even if `func` calls callback again, values from second and consecutive
  51. * calls will never appear on the stream. If you need to handle functions
  52. * that call callbacks multiple times, check out {@link fromEvent} or
  53. * {@link fromEventPattern} instead.
  54. *
  55. * Note that `bindNodeCallback` can be used in non-Node.js environments as well.
  56. * "Node.js-style" callbacks are just a convention, so if you write for
  57. * browsers or any other environment and API you use implements that callback style,
  58. * `bindNodeCallback` can be safely used on that API functions as well.
  59. *
  60. * Remember that Error object passed to callback does not have to be an instance
  61. * of JavaScript built-in `Error` object. In fact, it does not even have to an object.
  62. * Error parameter of callback function is interpreted as "present", when value
  63. * of that parameter is truthy. It could be, for example, non-zero number, non-empty
  64. * string or boolean `true`. In all of these cases resulting Observable would error
  65. * with that value. This means usually regular style callbacks will fail very often when
  66. * `bindNodeCallback` is used. If your Observable errors much more often then you
  67. * would expect, check if callback really is called in Node.js-style and, if not,
  68. * switch to {@link bindCallback} instead.
  69. *
  70. * Note that even if error parameter is technically present in callback, but its value
  71. * is falsy, it still won't appear in array emitted by Observable.
  72. *
  73. * ## Examples
  74. *
  75. * Read a file from the filesystem and get the data as an Observable
  76. *
  77. * ```ts
  78. * import * as fs from 'fs';
  79. * const readFileAsObservable = bindNodeCallback(fs.readFile);
  80. * const result = readFileAsObservable('./roadNames.txt', 'utf8');
  81. * result.subscribe(x => console.log(x), e => console.error(e));
  82. * ```
  83. *
  84. * Use on function calling callback with multiple arguments
  85. *
  86. * ```ts
  87. * someFunction((err, a, b) => {
  88. * console.log(err); // null
  89. * console.log(a); // 5
  90. * console.log(b); // "some string"
  91. * });
  92. * const boundSomeFunction = bindNodeCallback(someFunction);
  93. * boundSomeFunction()
  94. * .subscribe(value => {
  95. * console.log(value); // [5, "some string"]
  96. * });
  97. * ```
  98. *
  99. * Use on function calling callback in regular style
  100. *
  101. * ```ts
  102. * someFunction(a => {
  103. * console.log(a); // 5
  104. * });
  105. * const boundSomeFunction = bindNodeCallback(someFunction);
  106. * boundSomeFunction()
  107. * .subscribe(
  108. * value => {} // never gets called
  109. * err => console.log(err) // 5
  110. * );
  111. * ```
  112. *
  113. * @see {@link bindCallback}
  114. * @see {@link from}
  115. *
  116. * @param callbackFunc Function with a Node.js-style callback as the last parameter.
  117. * @param resultSelector A mapping function used to transform callback events.
  118. * @param scheduler The scheduler on which to schedule the callbacks.
  119. * @return A function which returns the Observable that delivers the same values the
  120. * Node.js callback would deliver.
  121. */
  122. export function bindNodeCallback(
  123. callbackFunc: (...args: [...any[], (err: any, ...res: any) => void]) => void,
  124. resultSelector?: ((...args: any[]) => any) | SchedulerLike,
  125. scheduler?: SchedulerLike
  126. ): (...args: any[]) => Observable<any> {
  127. return bindCallbackInternals(true, callbackFunc, resultSelector, scheduler);
  128. }