-
Notifications
You must be signed in to change notification settings - Fork 64
/
Promise.txt
574 lines (468 loc) · 20.5 KB
/
Promise.txt
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
*vital/Async/Promise.txt* an asynchronous operation like ES6 Promise
Maintainer: rhysd <[email protected]>
==============================================================================
CONTENTS *Vital.Async.Promise-contents*
INTRODUCTION |Vital.Async.Promise-introduction|
REQUIREMENTS |Vital.Async.Promise-requirements|
EXAMPLE |Vital.Async.Promise-example|
CONSTANTS |Vital.Async.Promise-constants|
FUNCTIONS |Vital.Async.Promise-functions|
OBJECTS |Vital.Async.Promise-objects|
Promise Object |Vital.Async.Promise-objects-Promise|
Exception Object |Vital.Async.Promise-objects-Exception|
==============================================================================
INTRODUCTION *Vital.Async.Promise-introduction*
*Vital.Async.Promise* is a library to represent the eventual completion or
failure of an asynchronous operation. APIs are aligned to ES6 Promise. If you
already know them, you can start to use this library easily.
Instead of callbacks, Promise provides:
- a guarantee that all operations are asynchronous. Functions given to .then()
method or .catch() method is executed on next tick (or later) using
|timer_start()|.
- chaining asynchronous operations. Chained operation's order is sequentially
run and the order is guaranteed.
- persistent error handling using .catch() method. Please be careful of
floating Promise. All Promise should have .catch() call not to squash an
exception.
- flow control such as awaiting all Promise objects completed or selecting
the fastest one of Promises objects.
If you know the detail of APIs, documents for ES6 Promise at Mozilla Developer
Network and ECMA-262 specs would be great.
Mozilla Developer Network:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
ECMA-262:
https://www.ecma-international.org/publications/standards/Ecma-262.htm
==============================================================================
REQUIREMENTS *Vital.Async.Promise-requirements*
|Vital.Async.Promise| requires |lambda| and |timers| features.
So Vim 8.0 or later is required. The recent version of Neovim also supports
them.
==============================================================================
EXAMPLE *Vital.Async.Promise-example*
Before explaining the detail of APIs, let's see actual examples.
(1) Timer *Vital.Async.Promise-example-timer*
>
let s:Promise = vital#vital#import('Async.Promise')
function! s:wait(ms)
return s:Promise.new({resolve -> timer_start(a:ms, resolve)})
endfunction
call s:wait(500).then({-> execute('echo "After 500ms"', '')})
<
One of most simple asynchronous operation is a timer. It calls a specified
callback when exceeding the timeout. "s:Promise.new" creates a new Promise
object with given callback. In the callback, function "resolve" (and
"reject" if needed) is passed. When the asynchronous operation is done (in
this case, when the timer is expired), call "resolve" on success or call
"reject" on failure.
(2) Next tick *Vital.Async.Promise-example-next-tick*
>
let s:Promise = vital#vital#import('Async.Promise')
function! s:next_tick()
return s:Promise.new({resolve -> timer_start(0, resolve)})
endfunction
call s:next_tick()
\.then({-> 'Execute lower priority tasks here'})
\.catch({err -> execute('echom err', '')})
<
By giving 0 to |timer_start()| as timeout, it waits for "next tick". It's the
first time when Vim waits for input. It means that Vim gives higher priority
to user input and executes the script (in the callback of |timer_start()|)
after.
(3) Job *Vital.Async.Promise-example-job*
>
let s:Promise = vital#vital#import('Async.Promise')
function! s:read(chan, part) abort
let out = []
while ch_status(a:chan, {'part' : a:part}) =~# 'open\|buffered'
call add(out, ch_read(a:chan, {'part' : a:part}))
endwhile
return join(out, "\n")
endfunction
function! s:sh(...) abort
let cmd = join(a:000, ' ')
return s:Promise.new({resolve, reject -> job_start(cmd, {
\ 'drop' : 'never',
\ 'close_cb' : {ch -> 'do nothing'},
\ 'exit_cb' : {ch, code ->
\ code ? reject(s:read(ch, 'err')) : resolve(s:read(ch, 'out'))
\ },
\ })})
endfunction
<
|job| is a feature to run commands asynchronously. But it is a bit hard to use
because it requires a callback. By wrapping it with Promise, it makes
further easier to use commands and handle errors asynchronously.
s:read() is just a helper function which reads all output of channel from
the job. So it's not so important.
Important part is "return ..." in s:sh(). It creates a Promise which starts
a job and resolves when the given command has done. It calls resolve() when
the command finished successfully with an output from stdout, and calls
reject() when the command failed with an output from stderr.
"ls -l" can be executed as follows:
>
call s:sh('ls', '-l')
\.then({out -> execute('echo "Output: " . out', '')})
\.catch({err -> execute('echo "Error: " . err', '')})
<
As the more complex example, following code clones 4 repositories and shows
a message when all of them has completed. When one of them fails, it shows
an error message without waiting for other operations.
>
call s:Promise.all([
\ s:sh('git', 'clone', 'https://github.com/thinca/vim-quickrun.git'),
\ s:sh('git', 'clone', 'https://github.com/tyru/open-browser-github.git'),
\ s:sh('git', 'clone', 'https://github.com/easymotion/vim-easymotion.git'),
\ s:sh('git', 'clone', 'https://github.com/rhysd/clever-f.vim.git'),
\]
\)
\.then({-> execute('echom "All repositories were successfully cloned!"', '')})
\.catch({err -> execute('echom "Failed to clone: " . err', '')})
<
s:Promise.all(...) awaits all given promises have completed, or one of them
has failed.
(4) Timeout *Vital.Async.Promise-example-timeout*
Let's see how Promise realizes timeout easily.
>
let s:Promise = vital#vital#import('Async.Promise')
call s:Promise.race([
\ s:sh('git', 'clone', 'https://github.com/vim/vim.git').then({-> v:false}),
\ s:wait(10000).then({-> v:true}),
\]).then({timed_out ->
\ execute('echom timed_out ? "Timeout!" : "Cloned!"', '')
\})
<
s:sh() and s:wait() are explained above. And .race() awaits one of given
Promise objects have finished.
The .race() awaits either s:sh(...) or s:wait(...) has completed or failed.
It means that it clones Vim repository from GitHub via git command, but if
it exceeds 10 seconds, it does not wait for the clone operation anymore.
By adding .then() and giving the result value (v:false or v:true here), you
can know whether the asynchronous operation was timed out or not in
succeeding .then() method. The parameter "timed_out" represents it.
(5) REST API call *Vital.Async.Promise-example-rest-api*
At last, let's see how Promise handles API call with |job| and curl
command. Here, we utilize previous "s:sh" function and encodeURIComponent()
function in |Vital.Web.HTTP| module to encode a query string.
>
let s:HTTP = vital#vital#import('Web.HTTP')
function! s:github_issues(query) abort
let q = s:HTTP.encodeURIComponent(a:query)
let url = 'https://api.github.com/search/issues?q=' . q
return s:sh('curl', url)
\.then({data -> json_decode(data)})
\.then({res -> has_key(res, 'items') ?
\ res.items :
\ execute('throw ' . string(res.message))})
endfunction
call s:github_issues('repo:vim/vim sort:reactions-+1')
\.then({issues -> execute('echom issues[0].url', '')})
\.catch({err -> execute('echom "ERROR: " . err', '')})
<
In this example, it searches the issue in Vim repository on GitHub which
gained the most :+1: reactions.
In s:github_issues(), it calls GitHub Issue Search API using curl command
and s:sh() function explained above. And it decodes the returned JSON by
|json_decode()| and checks the content. If the curl command failed or API
returned failure response, the Promise value will be rejected. The rejection
will be caught in .catch() method at the last line and an error message will
be shown.
==============================================================================
CONSTANTS *Vital.Async.Promise-constants*
TimeoutError *Vital.Async.Promise.TimeoutError*
An exception message string returned as {error} in a result list of
the |Vital.Async.Promise.wait()| function when timeout has reached.
==============================================================================
FUNCTIONS *Vital.Async.Promise-functions*
new({executor}) *Vital.Async.Promise.new()*
Creates a new Promise object with given {executor}.
{executor} is a |Funcref| which represents how to create a Promise
object. It is called _synchronously_. It receives two functions as
parameters. The first parameter is "resolve". It accepts one or zero
argument. By calling it in {executor}, new() returns a resolved
Promise object. The second parameter is "reject". It also accepts one
or zero argument. By calling it in {executor}, new() returns rejected
Promise object.
>
" Resolved Promise object with 42
let p = Promise.new({resolve -> resolve(42)})
" Rejected Promise object with 'ERROR!'
let p = Promise.new({_, reject -> reject('ERROR!')})
let p = Promise.new({-> execute('throw "ERROR!"')})
<
When another Promise object is passed to "resolve" or "reject"
function call, new() returns a pending Promise object which awaits
until the given other Promise object has finished.
If an exception is thrown in {executor}, new() returns a rejected
Promise object with the exception.
Calling "resolve" or "reject" more than once does not affect.
If "resolve" or "reject" is called with no argument, it resolves a
Promise object with |v:null|.
>
" :echo outputs 'v:null'
Promise.new({resolve -> resolve()})
\.then({x -> execute('echo x', '')})
<
resolve([{value}]) *Vital.Async.Promise.resolve()*
Creates a resolved Promise object.
It is a helper function equivalent to calling "resolve" immediately in
new():
>
" Followings are equivalent
let p = Promise.resolve(42)
let p = Promise.new({resolve -> resolve(42)})
<
If {value} is a Promise object, it resolves/rejects with a value which
given Promise object resolves/rejects with.
>
call Promise.resolve(Promise.resolve(42))
\.then({x -> execute('echo x', '')})
" Outputs '42'
call Promise.resolve(Promise.reject('ERROR!'))
\.catch({reason -> execute('echo reason', '')})
" Outputs 'ERROR!'
<
reject([{value}]) *Vital.Async.Promise.reject()*
Creates a rejected Promise object.
It is a helper function equivalent to calling "reject" immediately in
new():
>
" Followings are equivalent
let p = Promise.reject('Rejected!')
let p = Promise.new({_, reject -> reject('Rejected!')})
<
all({promises}) *Vital.Async.Promise.all()*
Creates a Promise object which awaits all of {promises} has completed.
It resolves the Promise object with a list of results of {promises} as
following:
>
call Promise.all([Promise.resolve(1), Promise.resolve('foo')])
\.then({arr -> execute('echo arr', '')})
" It shows [1, 'foo']
<
If one of them is rejected, it does not await other Promise objects
and the Promise object is rejected immediately.
>
call Promise.all([Promise.resolve(1), Promise.reject('ERROR!')])
\.catch({err -> execute('echo err', '')})
" It shows 'ERROR!'
<
If an empty list is given, it is equivalent to Promise.resolve([]).
race({promises}) *Vital.Async.Promise.race()*
Creates a Promise object which resolves or rejects as soon as one of
{promises} resolves or rejects.
>
call Promise.race([
\ Promise.new({resolve -> timer_start(50, {-> resolve('first')})}),
\ Promise.new({resolve -> timer_start(100, {-> resolve('second')})}),
\])
\.then({v -> execute('echo v', '')})
" It outputs 'first'
call Promise.race([
\ Promise.new({resolve -> timer_start(50, {-> execute('throw "ERROR!"')})}),
\ Promise.new({resolve -> timer_start(100, {-> resolve('second')})}),
\])
\.then({v -> execute('echo v', '')})
\.catch({e -> execute('echo e', '')})
" It outputs 'ERROR!'
<
If {promises} is an empty list, the returned Promise object will never
be resolved or rejected.
wait({promise}[, {options}]) *Vital.Async.Promise.wait()*
Waits synchronously until a given {promise} has become resolved and
returns a [{result}, {error}] list.
The {result} is a {value} passed to |Vital.Async.Promise.resolve()|
when a given {promise} has resolved. Otherwise it is |v:null|.
The {error} is a {value} passed to |Vital.Async.Promise.reject()|
when a given {promise} has rejected or |Async.Promise.TimeoutError|
when a given {timeout} has passed. Otherwise it is |v:null|.
The following {options} are available
"timeout" Timeout in milliseconds. When timeout, the function
returns a [|v:null||, |Async.Promise.TimeoutError|]
list.
When it is |v:null|, the function waits a given
{promise} for ever.
Default: v:null
"interval" Interval delay of an internal loop in milliseconds.
Default: 30
>
let [result, error] = Promise.wait(p, { 'timeout': 1000 })
if error ==# Promise.TimeoutError
echo 'Timeout!'
elseif error isnot# v:null
echoerr "Failed:" . string(error)
else
echo "Success:" . string(result)
endif
<
For convenience, users can directly specify the "timeout" in the
second argument like
>
call Promise.wait(p, 1000)
" Is equivalent to call Promise.wait(p, {'timeout': 1000})
>
chain({promise_factories}) *Vital.Async.Promise.chain()*
Chain promises produced by {promise_factories} (|List| of |Function|)
and return a promise which resolves to a result |List| which contains
result of each produced promises.
It is like an asynchronous sequential call. It rejects when one of
function in {promise_factories} has failed or produced promises
rejects. Note that it stops producing promises by functions after
rejection.
>
let fs = [
\ { -> Promise.new({ r -> timer_start(50, { -> r('1') })})},
\ { -> Promise.new({ r -> timer_start(50, { -> r('2') })})},
\ { -> Promise.new({ r -> timer_start(50, { -> r('3') })})},
\]
call Promise.chain(fs)
" --------1--------2--------3----> RESOLVE
" 50ms 100ms 150ms
let fs = [
\ { -> Promise.new({ r -> timer_start(50, { -> r('1') })})},
\ { -> execute('throw "Error"') },
\ { -> Promise.new({ r -> timer_start(50, { -> r('3') })})},
\]
call Promise.chain(fs)
" --------1----> REJECT
" 50ms
let fs = [
\ { -> Promise.new({ r -> timer_start(50, { -> r('1') })})},
\ { -> Promise.new({ _, rj -> timer_start(50, { -> rj('2') })})},
\ { -> Promise.new({ r -> timer_start(50, { -> r('3') })})},
\]
call Promise.chain(fs)
" --------1--------2----> REJECT
" 50ms 100ms
<
on_unhandled_rejection({callback}) *Vital.Async.Promise.on_unhandled_rejection*
Set callback to catch all unhandled rejected promise's result.
If {callback} throws error, |Async.Promise| does not handle it.
The {callback} is |Funcref|, it's argument can be unhandled thrown error or unhandled rejected value.
Note:
This callback will called even if you using |Vital.Async.Promise.wait()|.
If you want to clear callback, you can use following codes.
>
call Promise.on_unhandled_rejection(Promise.noop)
<
is_promise({value}) *Vital.Async.Promise.is_promise()*
Returns TRUE when {value} is a Promise object. Otherwise, returns
FALSE.
is_available() *Vital.Async.Promise.is_available()*
Returns TRUE when requirements for using |Vital.Async.Promise| are
met. Please look at |Vital.Async.Promise-requirements| to know the
detail of the requirements.
Otherwise, returns FALSE.
>
if Promise.is_available()
" Asynchronous operations using Promise
else
" Fallback into synchronous operations
endif
<
==============================================================================
OBJECTS *Vital.Async.Promise-objects*
------------------------------------------------------------------------------
Promise Object *Vital.Async.Promise-objects-Promise*
Promise object represents the eventual completion or failure of an
asynchronous operation. It represents one of following states:
- Operation has not done yet
- Operation has completed successfully
- Operation has failed with an error
*Vital.Async.Promise-Promise.then()*
{promise}.then([{onResolved} [, {onRejected}]])
Creates a new Promise object which is resolved/rejected after
{promise} is resolved or rejected. {onResolved} and {onRejected} must
be |Funcref| and they are guaranteed to be called __asynchronously__.
>
echo 'hi'
call Promise.new({resolve -> execute('echo "halo" | call resolve(42)', '')})
\.then({-> execute('echo "bye"', '')}, {-> execute('echo "ah"', '')})
echo 'yo'
<
Above script outputs messages as following:
>
hi
halo
yo
bye
<
If {onResolved} is specified, it is called after {promise} is
resolved. When {onResolved} returns non-Promise value, the returned
Promise object from .then() is resolved with it.
When {onResolved} returns a Promise object, the returned Promise
object awaits until the Promise object has finished.
If {onRejected} is specified, it is called after {promise} is
rejected. When {onRejected} returns non-Promise value, the returned
Promise object from .then() is resolved with it.
When {onRejected} returns a Promise object, the returned Promise
object awaits until the Promise object has finished.
When an exception is thrown in {onResolved} or {onRejected}, the
returned Promise object from .then() will be rejected with an
exception object.
Please read |Vital.Async.Promise-objects-Exception| to know an
exception object.
>
" Both followings create a rejected Promise value asynchronously
call Promise.resolve(42).then({-> execute('throw "ERROR!"')})
call Promise.resolve(42).then({-> Promise.reject('ERROR!')})
<
{onResolved} and {onRejected} can be |v:null|.
{promise}.catch([{onRejected}]) *Vital.Async.Promise-Promise.catch()*
It is a shortcut function of calling .then() where the first argument
is |v:null|.
>
" Followings are equal
call Promise.reject('ERROR').then(v:null, {msg -> execute('echo msg', '')})
call Promise.reject('ERROR').catch({msg -> execute('echo msg', '')})
<
{promise}.finally([{onFinally}]) *Vital.Async.Promise-Promise.finally()*
It returns a Promise and the passed callback is called once the
promise is settled, whether fulfilled or rejected.
This provides a way for code that must be executed once the promise
has been dealt with to be run whether it was fulfilled successfully or
rejected. {onFinally} is a |Funcref| which has no parameter.
>
" Both followings echo 'on finally'
call Promise.resolve(42).finally({-> execute('echo "on finally"', '')})
call Promise.reject('ERROR!').finally({-> execute('echo "on finally"', '')})
<
|:throw| in the {onFinally} callback will reject the new promise with
the thrown error.
Unlike passing the callback to both 1st and 2nd parameters of
.then(), it propagates its receiver's result.
>
" Following echoes 42
call Promise.resolve(42)
\.finally({-> v:null})
\.then({x -> execute('echo x', '')})
<
Note:
As an above code, .finally() is different from .then() in terms of
the resolved/rejected value. `Promise.resolve(42).finally()` resolves
with 42, but `Promise.resolve(42).then({-> v:null}, {-> v:null})`
resolves with v:null.
------------------------------------------------------------------------------
Exception Object *Vital.Async.Promise-objects-Exception*
Exception object represents an exception of Vim script. Since Vim script's
|v:exception| is a |String| value and a stack trace of the exception is
separated to |v:throwpoint| variable, it does not fit Promise API.
So we need to define our own exception object. It is passed to {onRejected}
parameter of .then() or .catch() method.
Example:
>
call Promise.new({-> execute('throw "ERROR!"')})
\.catch({ex -> execute('echo ex', '')})
" Output:
" {'exception': 'ERROR!', 'throwpoint': '...'}
call Promise.new({-> 42 == []})
\.catch({ex -> execute('echo ex', '')})
" Output:
" {'exception': 'Vim(return):E691: ...', 'throwpoint': '...'}
<
Exception object has two fields; "exception" and "throwpoint".
"exception" is an error message. It's corresponding to |v:exception|. And
"throwpoint" is a stack trace of the caught exception. It's corresponding to
|v:throwpoint|.
==============================================================================
vim:tw=78:fo=tcq2mM:ts=8:ft=help:norl