-
Notifications
You must be signed in to change notification settings - Fork 28
/
utils.js
371 lines (353 loc) · 10.9 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// This file contains all the non-ES6-standard helpers based on promise.
module.exports = {
/**
* A function that helps run functions under a concurrent limitation.
* To run functions sequentially, use `yaku/lib/flow`.
* @param {Int} limit The max task to run at a time. It's optional.
* Default is `Infinity`.
* @param {Iterable} list Any [iterable](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) object. It should be a lazy iteralbe object,
* don't pass in a normal Array with promises.
* @return {Promise}
* @example
* ```js
* var kit = require('nokit');
* var all = require('yaku/lib/all');
*
* var urls = [
* 'http://a.com',
* 'http://b.com',
* 'http://c.com',
* 'http://d.com'
* ];
* var tasks = function * () {
* var i = 0;
* yield kit.request(url[i++]);
* yield kit.request(url[i++]);
* yield kit.request(url[i++]);
* yield kit.request(url[i++]);
* }();
*
* all(tasks).then(() => kit.log('all done!'));
*
* all(2, tasks).then(() => kit.log('max concurrent limit is 2'));
*
* all(3, { next: () => {
* var url = urls.pop();
* return {
* done: !url,
* value: url && kit.request(url)
* };
* } })
* .then(() => kit.log('all done!'));
* ```
*/
all: require('./all'),
/**
* Similar with the `Promise.race`, but only rejects when every entry rejects.
* @param {iterable} iterable An iterable object, such as an Array.
* @return {Yaku}
* @example
* ```js
* var any = require('yaku/lib/any');
* any([
* 123,
* Promise.resolve(0),
* Promise.reject(new Error("ERR"))
* ])
* .then((value) => {
* console.log(value); // => 123
* });
* ```
*/
any: require('./any'),
/**
* Generator based async/await wrapper.
* @param {Generator} gen A generator function
* @return {Yaku}
* @example
* ```js
* var async = require('yaku/lib/async');
* var sleep = require('yaku/lib/sleep');
*
* var fn = async(function * () {
* return yield sleep(1000, 'ok');
* });
*
* fn().then(function (v) {
* console.log(v);
* });
* ```
*/
async: require('./async'),
/**
* If a function returns promise, convert it to
* node callback style function.
* @param {Function} fn
* @param {Any} self The `this` to bind to the fn.
* @return {Function}
*/
callbackify: require('./callbackify'),
/**
* **deprecate** Create a `jQuery.Deferred` like object.
* It will cause some buggy problems, please don't use it.
*/
Deferred: require('./Deferred'),
/**
* Creates a function that is the composition of the provided functions.
* See `yaku/lib/async`, if you need concurrent support.
* @param {Iterable} list Any [iterable](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) object. It should be a lazy iteralbe object,
* don't pass in a normal Array with promises.
* @return {Function} `(val) -> Promise` A function that will return a promise.
* @example
* It helps to decouple sequential pipeline code logic.
* ```js
* var kit = require('nokit');
* var flow = require('yaku/lib/flow');
*
* function createUrl (name) {
* return "http://test.com/" + name;
* }
*
* function curl (url) {
* return kit.request(url).then((body) => {
* kit.log('get');
* return body;
* });
* }
*
* function save (str) {
* kit.outputFile('a.txt', str).then(() => {
* kit.log('saved');
* });
* }
*
* var download = flow(createUrl, curl, save);
* // same as "download = flow([createUrl, curl, save])"
*
* download('home');
* ```
* @example
* Walk through first link of each page.
* ```js
* var kit = require('nokit');
* var flow = require('yaku/lib/flow');
*
* var list = [];
* function iter (url) {
* return {
* done: !url,
* value: url && kit.request(url).then((body) => {
* list.push(body);
* var m = body.match(/href="(.+?)"/);
* if (m) return m[0];
* });
* };
* }
*
* var walker = flow(iter);
* walker('test.com');
* ```
*/
flow: require('./flow'),
/**
* Enable a helper to catch specific error type.
* It will be directly attach to the prototype of the promise.
* @param {class} type
* @param {Function} onRejected
* @return {Promise}
* ```js
* var Promise = require('yaku');
* require('yaku/lib/guard');
*
* class AnError extends Error {
* }
*
* Promise.reject(new AnError('hey'))
* .guard(AnError, (err) => {
* // only log AnError type
* console.log(err);
* })
* .then(() => {
* console.log('done');
* })
* .guard(Error, (err) => {
* // log all error type
* console.log(err)
* });
* ```
*/
guard: require('./guard'),
/**
* Just like `Promise.all`, but you pass in a key-value dict,
* after every value is resolved, it will resolve a k-v dict.
* @param {Object} dict
* @return {Promise}
* ```js
* var hash = require('yaku/lib/hash');
* var sleep = require('yaku/lib/sleep');
*
* hash({
* a: sleep(100, 'a'),
* b: sleep(200, 'b')
* }).then((dict) => { // will resolve after 200ms, not 300ms
* console.log(dict.a, dict.b)
* })
* ```
*/
hash: require('./hash'),
/**
* if-else helper
* @param {Promise} cond
* @param {Function} trueFn
* @param {Function} falseFn
* @return {Promise}
* @example
* ```js
* var Promise = require('yaku');
* var yutils = require('yaku/lib/utils');
*
* yutils.if(Promise.resolve(false), () => {
* // true
* }, () => {
* // false
* })
* ```
*/
'if': require('./if'),
/**
* **deprecate** Check if an object is a promise-like object.
* Don't use it to coercive a value to Promise, instead use `Promise.resolve`.
* @param {Any} obj
* @return {Boolean}
*/
isPromise: require('./isPromise'),
/**
* Create a promise that never ends.
* @return {Promise} A promise that will end the current pipeline.
*/
never: require('./never'),
/**
* Convert a node callback style function to a function that returns
* promise when the last callback is not supplied.
* @param {Function} fn
* @param {Any} self The `this` to bind to the fn.
* @return {Function}
* @example
* ```js
* var promisify = require('yaku/lib/promisify');
* function foo (val, cb) {
* setTimeout(() => {
* cb(null, val + 1);
* });
* }
*
* var bar = promisify(foo);
*
* bar(0).then((val) => {
* console.log val // output => 1
* });
*
* // It also supports the callback style.
* bar(0, (err, val) => {
* console.log(val); // output => 1
* });
* ```
*/
promisify: require('./promisify'),
/**
* Create a promise that will wait for a while before resolution.
* @param {Integer} time The unit is millisecond.
* @param {Any} val What the value this promise will resolve.
* @return {Promise}
* @example
* ```js
* var sleep = require('yaku/lib/sleep');
* sleep(1000).then(() => console.log('after one second'));
* ```
*/
sleep: require('./sleep'),
/**
* Read the `Observable` section.
* @type {Function}
*/
Observable: require('./Observable'),
/**
* Retry a function until it resolves before a mount of times, or reject with all
* the error states.
* @version_added v0.7.10
* @param {Number | Function} countdown How many times to retry before rejection.
* @param {Number} span Optional. How long to wait before each retry in millisecond.
* When it's a function `(errs) => Boolean | Promise.resolve(Boolean)`,
* you can use it to create complex countdown logic,
* it can even return a promise to create async countdown logic.
* @param {Function} fn The function can return a promise or not.
* @param {Any} this Optional. The context to call the function.
* @return {Function} The wrapped function. The function will reject an array
* of reasons that throwed by each try.
* @example
* Retry 3 times before rejection, wait 1 second before each retry.
* ```js
* var retry = require('yaku/lib/retry');
* var { request } = require('nokit');
*
* retry(3, 1000, request)('http://test.com').then(
* (body) => console.log(body),
* (errs) => console.error(errs)
* );
* ```
* @example
* Here a more complex retry usage, it shows an random exponential backoff algorithm to
* wait and retry again, which means the 10th attempt may take 10 minutes to happen.
* ```js
* var retry = require('yaku/lib/retry');
* var sleep = require('yaku/lib/sleep');
* var { request } = require('nokit');
*
* function countdown (retries) {
* var attempt = 0;
* return async () => {
* var r = Math.random() * Math.pow(2, attempt) * 1000;
* var t = Math.min(r, 1000 * 60 * 10);
* await sleep(t);
* return attempt++ < retries;
* };
* }
*
* retry(countdown(10), request)('http://test.com').then(
* (body) => console.log(body),
* (errs) => console.error(errs)
* );
* ```
*/
retry: require('./retry'),
/**
* Throw an error to break the program.
* @param {Any} err
* @example
* ```js
* var ythrow = require('yaku/lib/throw');
* Promise.resolve().then(() => {
* // This error won't be caught by promise.
* ythrow('break the program!');
* });
* ```
*/
'throw': require('./throw'),
/**
* Create a promise that will reject after a while if the passed in promise
* doesn't settle first.
* @param {Promise} promise The passed promise to wait.
* @param {Integer} time The unit is millisecond.
* @param {Any} reason After time out, it will be the reject reason.
* @return {Promise}
* @example
* ```js
* var sleep = require('yaku/lib/sleep');
* var timeout = require('yaku/lib/timeout');
* timeout(sleep(500), 100)["catch"]((err) => {
* console.error(err);
* });
* ```
*/
timeout: require('./timeout')
};