node.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import Promise from './promise';
  2. import {
  3. noop,
  4. resolve,
  5. reject
  6. } from './-internal';
  7. import { isArray } from './utils';
  8. function Result() {
  9. this.value = undefined;
  10. }
  11. const ERROR = new Result();
  12. const GET_THEN_ERROR = new Result();
  13. function getThen(obj) {
  14. try {
  15. return obj.then;
  16. } catch(error) {
  17. ERROR.value= error;
  18. return ERROR;
  19. }
  20. }
  21. function tryApply(f, s, a) {
  22. try {
  23. f.apply(s, a);
  24. } catch(error) {
  25. ERROR.value = error;
  26. return ERROR;
  27. }
  28. }
  29. function makeObject(_, argumentNames) {
  30. let obj = {};
  31. let length = _.length;
  32. let args = new Array(length);
  33. for (let x = 0; x < length; x++) {
  34. args[x] = _[x];
  35. }
  36. for (let i = 0; i < argumentNames.length; i++) {
  37. let name = argumentNames[i];
  38. obj[name] = args[i + 1];
  39. }
  40. return obj;
  41. }
  42. function arrayResult(_) {
  43. let length = _.length;
  44. let args = new Array(length - 1);
  45. for (let i = 1; i < length; i++) {
  46. args[i - 1] = _[i];
  47. }
  48. return args;
  49. }
  50. function wrapThenable(then, promise) {
  51. return {
  52. then: function(onFulFillment, onRejection) {
  53. return then.call(promise, onFulFillment, onRejection);
  54. }
  55. };
  56. }
  57. /**
  58. `RSVP.denodeify` takes a 'node-style' function and returns a function that
  59. will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the
  60. browser when you'd prefer to use promises over using callbacks. For example,
  61. `denodeify` transforms the following:
  62. ```javascript
  63. let fs = require('fs');
  64. fs.readFile('myfile.txt', function(err, data){
  65. if (err) return handleError(err);
  66. handleData(data);
  67. });
  68. ```
  69. into:
  70. ```javascript
  71. let fs = require('fs');
  72. let readFile = RSVP.denodeify(fs.readFile);
  73. readFile('myfile.txt').then(handleData, handleError);
  74. ```
  75. If the node function has multiple success parameters, then `denodeify`
  76. just returns the first one:
  77. ```javascript
  78. let request = RSVP.denodeify(require('request'));
  79. request('http://example.com').then(function(res) {
  80. // ...
  81. });
  82. ```
  83. However, if you need all success parameters, setting `denodeify`'s
  84. second parameter to `true` causes it to return all success parameters
  85. as an array:
  86. ```javascript
  87. let request = RSVP.denodeify(require('request'), true);
  88. request('http://example.com').then(function(result) {
  89. // result[0] -> res
  90. // result[1] -> body
  91. });
  92. ```
  93. Or if you pass it an array with names it returns the parameters as a hash:
  94. ```javascript
  95. let request = RSVP.denodeify(require('request'), ['res', 'body']);
  96. request('http://example.com').then(function(result) {
  97. // result.res
  98. // result.body
  99. });
  100. ```
  101. Sometimes you need to retain the `this`:
  102. ```javascript
  103. let app = require('express')();
  104. let render = RSVP.denodeify(app.render.bind(app));
  105. ```
  106. The denodified function inherits from the original function. It works in all
  107. environments, except IE 10 and below. Consequently all properties of the original
  108. function are available to you. However, any properties you change on the
  109. denodeified function won't be changed on the original function. Example:
  110. ```javascript
  111. let request = RSVP.denodeify(require('request')),
  112. cookieJar = request.jar(); // <- Inheritance is used here
  113. request('http://example.com', {jar: cookieJar}).then(function(res) {
  114. // cookieJar.cookies holds now the cookies returned by example.com
  115. });
  116. ```
  117. Using `denodeify` makes it easier to compose asynchronous operations instead
  118. of using callbacks. For example, instead of:
  119. ```javascript
  120. let fs = require('fs');
  121. fs.readFile('myfile.txt', function(err, data){
  122. if (err) { ... } // Handle error
  123. fs.writeFile('myfile2.txt', data, function(err){
  124. if (err) { ... } // Handle error
  125. console.log('done')
  126. });
  127. });
  128. ```
  129. you can chain the operations together using `then` from the returned promise:
  130. ```javascript
  131. let fs = require('fs');
  132. let readFile = RSVP.denodeify(fs.readFile);
  133. let writeFile = RSVP.denodeify(fs.writeFile);
  134. readFile('myfile.txt').then(function(data){
  135. return writeFile('myfile2.txt', data);
  136. }).then(function(){
  137. console.log('done')
  138. }).catch(function(error){
  139. // Handle error
  140. });
  141. ```
  142. @method denodeify
  143. @static
  144. @for RSVP
  145. @param {Function} nodeFunc a 'node-style' function that takes a callback as
  146. its last argument. The callback expects an error to be passed as its first
  147. argument (if an error occurred, otherwise null), and the value from the
  148. operation as its second argument ('function(err, value){ }').
  149. @param {Boolean|Array} [options] An optional paramter that if set
  150. to `true` causes the promise to fulfill with the callback's success arguments
  151. as an array. This is useful if the node function has multiple success
  152. paramters. If you set this paramter to an array with names, the promise will
  153. fulfill with a hash with these names as keys and the success parameters as
  154. values.
  155. @return {Function} a function that wraps `nodeFunc` to return an
  156. `RSVP.Promise`
  157. @static
  158. */
  159. export default function denodeify(nodeFunc, options) {
  160. let fn = function() {
  161. let self = this;
  162. let l = arguments.length;
  163. let args = new Array(l + 1);
  164. let promiseInput = false;
  165. for (let i = 0; i < l; ++i) {
  166. let arg = arguments[i];
  167. if (!promiseInput) {
  168. // TODO: clean this up
  169. promiseInput = needsPromiseInput(arg);
  170. if (promiseInput === GET_THEN_ERROR) {
  171. let p = new Promise(noop);
  172. reject(p, GET_THEN_ERROR.value);
  173. return p;
  174. } else if (promiseInput && promiseInput !== true) {
  175. arg = wrapThenable(promiseInput, arg);
  176. }
  177. }
  178. args[i] = arg;
  179. }
  180. let promise = new Promise(noop);
  181. args[l] = function(err, val) {
  182. if (err)
  183. reject(promise, err);
  184. else if (options === undefined)
  185. resolve(promise, val);
  186. else if (options === true)
  187. resolve(promise, arrayResult(arguments));
  188. else if (isArray(options))
  189. resolve(promise, makeObject(arguments, options));
  190. else
  191. resolve(promise, val);
  192. };
  193. if (promiseInput) {
  194. return handlePromiseInput(promise, args, nodeFunc, self);
  195. } else {
  196. return handleValueInput(promise, args, nodeFunc, self);
  197. }
  198. };
  199. fn.__proto__ = nodeFunc;
  200. return fn;
  201. }
  202. function handleValueInput(promise, args, nodeFunc, self) {
  203. let result = tryApply(nodeFunc, self, args);
  204. if (result === ERROR) {
  205. reject(promise, result.value);
  206. }
  207. return promise;
  208. }
  209. function handlePromiseInput(promise, args, nodeFunc, self){
  210. return Promise.all(args).then(args => {
  211. let result = tryApply(nodeFunc, self, args);
  212. if (result === ERROR) {
  213. reject(promise, result.value);
  214. }
  215. return promise;
  216. });
  217. }
  218. function needsPromiseInput(arg) {
  219. if (arg && typeof arg === 'object') {
  220. if (arg.constructor === Promise) {
  221. return true;
  222. } else {
  223. return getThen(arg);
  224. }
  225. } else {
  226. return false;
  227. }
  228. }