-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnotebook.jl
1622 lines (1341 loc) · 41.6 KB
/
notebook.jl
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### A Pluto.jl notebook ###
# v0.18.1
using Markdown
using InteractiveUtils
# ╔═╡ cbc47c58-c2d9-40da-a31f-5545fb470859
begin
function skip_as_script(m::Module)
if isdefined(m, :PlutoForceDisplay)
return getfield(m, :PlutoForceDisplay)
else
isdefined(m, :PlutoRunner) && parentmodule(m) === Main
end
end
"""
@skip_as_script expression
Marks a expression as Pluto-only, which means that it won't be executed when running outside Pluto. Do not use this for your own projects.
"""
macro skip_as_script(ex) skip_as_script(__module__) ? esc(ex) : nothing end
const developing = skip_as_script(@__MODULE__)
const PROJECT_ROOT = dirname(@__DIR__)
const TEST_DIR = joinpath(PROJECT_ROOT, "test")
if developing
import Pkg
new_env = mktempdir()
cp(TEST_DIR, new_env; force=true)
copy!(LOAD_PATH, ["@", PROJECT_ROOT])
Pkg.activate(new_env)
Pkg.instantiate()
# development dependencies
import Downloads
import JSON
using BenchmarkTools
using PlutoTest
else
macro test(e...); nothing; end
macro benchmark(e...); nothing; end
macro test_broken(e...); nothing; end
macro test_throws(e...); nothing; end
end
using HypertextLiteral
import AbstractPlutoDingetjes
const pkg_setup = "done"
if developing
html"""
<blockquote style='font-family: system-ui; font-size: 1.5rem; font-weight: 600;'>Development environment active 🚀</blockquote>
"""
end
end
# ╔═╡ da12a2c8-a631-4da8-be4e-87cc1e1f124c
md"""
# Promises.jl: *JavaScript-inspired async*
> #### Summary:
>
> A **`Promise{T}`** is a container for a value **that will arrive in the future**.
>
> You can **await** Promises, and you can **chain** processing steps with `.then` and `.catch`, each producing a new `Promise`.
"""
# ╔═╡ f0567e34-6fb8-4509-80e7-532e0464f1bd
md"""
Let's look at an example, using Promises.jl to download data in the background:
"""
# ╔═╡ 1cf696fd-6fa4-4e93-8132-63d89d902f95
username = "JuliaLang"
# ╔═╡ 7e24cd7d-6f1c-47e2-b0a3-d8f81a4e7167
md"""
The result is a *pending promise*: it might still running in the background!
"""
# ╔═╡ 82f259ca-0e35-4278-ac46-aed2fdb87857
md"""
You can use `@await` to wait for it to finish, and get its value:
"""
# ╔═╡ d3b5ee70-81d2-425d-9fb0-4c9a42ea4674
md"""
Since the original Promise `download_result` was asynchronous, this newly created `Promise` is also asynchronous! By chaining the operations `read` and `JSON.parse`, you are "queing" them to run in the background.
"""
# ╔═╡ 2614a13c-3454-444f-86ac-fedd6cb58c3c
md"""
If you `@await` a Promise that has rejected, the rejected value will be rethrown as an error:
"""
# ╔═╡ 1d66a02b-5c9c-4c3a-bfbc-b11fc7196c3a
md"""
(A shorthand function is available to create promises that immediately reject or resolve, like we did above: `Promises.resolve(value)` and `Promises.reject(value)`.)
"""
# ╔═╡ 038949f4-3f99-496e-a3c7-f980f2fa92d2
md"""
2. The `.catch` is the opposite of `.then`: it is used to handle rejected values.
"""
# ╔═╡ bdb0e349-b043-4a07-9dc8-1f2ea587ac2f
md"""
Here is a little table:
| | `.then` | `.catch` |
| --- | --- | --- |
| On a **resolved** Promise: | Runs | *Skipped* |
| On a **rejected** Promise: | *Skipped* | Runs |
"""
# ╔═╡ 74cdad42-7f54-4da3-befe-a67c969217ae
md"""
This information is available to the Julia compiler, which means that it can do smart stuff!
"""
# ╔═╡ ae4e308e-83be-4e0b-a0a4-96677dcffa22
md"""
Trying to resolve to another type will reject the Promise:
"""
# ╔═╡ bcaaf4f0-cb32-4136-aaec-3259ef6b383d
md"""
#### Automatic types
Julia is smart, and it can automatically determine the type of chained Promises using static analysis!
"""
# ╔═╡ 580d9608-fb50-4845-b3b2-4195cdb41d67
# ╔═╡ 530e9bf7-bd09-4978-893a-c945ca15e508
md"""
# Implementation
"""
# ╔═╡ bc985d7d-0e31-4754-84a9-67f653248b7c
cleanup_backtrace(x) = x
# ╔═╡ 3e65077d-8c4e-4531-a6fa-d177fd7ed1ea
function cleanup_backtrace(val::CapturedException)
try
stack = [s for (s, _) in val.processed_bt]
pluto_stuff_index = findfirst(val.processed_bt) do (f,_)
occursin("function_wrapped_cell", String(f.func))
end
stack = if pluto_stuff_index === nothing
val.processed_bt
else
val.processed_bt[begin:pluto_stuff_index-1]
end
# here = replace(@__FILE__, r"#==#.*" => "")
# stack_really = filter(stack) do (f,_)
# !occursin(here, String(f.file))
# end
stack_really = stack
CapturedException(val.ex, stack_really)
catch e
val
end
end
# ╔═╡ 49a8beb7-6a97-4c46-872e-e89822108f39
begin
Base.@kwdef struct Promise{T}
resolved_val::Ref{Union{Nothing,Some{T}}}=Ref{Union{Nothing,Some{T}}}(nothing)
rejected_val::Ref{Union{Nothing,Some{Any}}}=Ref{Union{Nothing,Some{Any}}}(nothing)
done::Channel{Nothing}=Channel{Nothing}(1)
end
function Promise{T}(f::Function) where T
p = Promise{T}()
begin
function resolve(val=nothing)
if !isready(p.done)
if val isa Promise
# TODO: this leaks memory maybe because one will keep hanging?
val.then(resolve)
val.catch(reject)
return val
elseif val isa T
p.resolved_val[] = Some{T}(val)
else
p.rejected_val[] = Some{Any}(cleanup_backtrace(CapturedException(
ArgumentError("Can only resolve with values of type $T."),
backtrace())
))
end
put!(p.done, nothing)
end
val
end
function reject(val=nothing)
if !isready(p.done)
p.rejected_val[] = Some{Any}(val)
put!(p.done, nothing)
end
val
end
try
t = f(resolve, reject)
# if t isa Task
# wait(t)
# end
catch e
reject(cleanup_backtrace(CapturedException(e, catch_backtrace())))
end
end
p
end
function Promise(f::Function)
Promise{Any}(f)
end
Base.eltype(p::Promise{T}) where T = T
isresolved(p::Promise) = isready(p) && p.resolved_val[] !== nothing
isrejected(p::Promise) = isready(p) && p.rejected_val[] !== nothing
Base.isready(p::Promise) = isready(p.done)
function promise_then(p::Promise{T1}, f::Function) where T1
if isready(p.done)
if isresolved(p)
try
r = f(something(p.resolved_val[]))
promise_resolved(r)
catch e
promise_rejected(cleanup_backtrace(CapturedException(e, catch_backtrace())))
end
else
p
end
else
T2 = Core.Compiler.return_type(f, (T1,))
T3 = promise_eltype_recursive(T2)
Promise{T3}() do resolve, reject
@async begin
wait(p.done)
rv = p.resolved_val[]
if rv !== nothing
try
resolve(f(something(rv)))
catch e
reject(cleanup_backtrace(CapturedException(e, catch_backtrace())))
end
else
reject(something(p.rejected_val[]))
end
end
end
end
end
function promise_catch(p::Promise{T1}, f::Function) where T1
T2 = Core.Compiler.return_type(f, (Any,))
Promise{Union{T1,T2}}() do resolve, reject
isready(p.done) || wait(p.done)
if isresolved(p)
resolve(something(p.resolved_val[]))
else
resolve(f(something(p.rejected_val[])))
end
end
end
function Base.fetch(p::Promise{T})::T where T
isready(p.done) || wait(p.done)
if (rv = p.resolved_val[]) !== nothing
something(rv)
else
throw(something(p.rejected_val[]))
end
end
function Base.wait(p::Promise)
isready(p.done) || wait(p.done)
if p.rejected_val[] !== nothing
throw(something(p.rejected_val[]))
end
nothing
end
function Base.:(==)(a::Promise{T}, b::Promise{T}) where T
isready(a) == isready(b) &&
a.resolved_val[] == b.resolved_val[] &&
a.rejected_val[] == b.rejected_val[]
end
Base.hash(p::Promise) = hash((
typeof(p),
isready(p),
p.resolved_val[],
p.rejected_val[],
))
Base.promote_rule(::Type{Promise{T}}, ::Type{Promise{S}}) where {T,S} = Promise{promote_type(T,S)}
function Base.convert(PT::Type{Promise{T}}, p::Promise{S}) where {T,S}
PT() do res, rej
p.then(val -> res(convert(T, val)))
p.catch(rej)
end
end
function done_channel()
c = Channel{Nothing}(1)
put!(c, nothing)
c
end
promise_resolved(p::Promise) = p
promise_resolved(x::T) where T =
Promise{T}(
resolved_val=Ref{Union{Nothing,Some{T}}}(Some{T}(x)),
done=done_channel(),
)
promise_rejected(x) =
Promise{Any}(
rejected_val=Ref{Union{Nothing,Some{Any}}}(Some{Any}(x)),
done=done_channel(),
)
# promise_value_recursive(x) = x
# promise_value_recursive(p::Promise) =
promise_eltype_recursive(T::Type) =
(T <: Promise) ? promise_eltype_recursive(eltype(T)) : T
function Base.getproperty(p::Promise{T1}, name::Symbol) where T1
if name === :then
f -> promise_then(p, f)
elseif name === :catch
f -> promise_catch(p, f)
else
getfield(p, name)
end
end
function Base.show(io::IO, m::MIME"text/plain", p::Promise)
summary(io, p)
if isresolved(p)
write(io, "( <resolved>: ")
show(io, m, fetch(p))
write(io, " )")
elseif isrejected(p)
write(io, "( <rejected>: ")
rej_val = something(p.rejected_val[])
if rej_val isa CapturedException
println(io)
showerror(io, rej_val)
println(io)
else
show(io, m, rej_val)
end
write(io, " )")
else
write(io, "( <pending> )")
end
end
function Base.show(io::IO, m::MIME"text/html", p::Promise)
typestr = sprint(summary, p; context=io)
state, display = if isresolved(p)
"resolved", p.resolved_val[]
elseif isrejected(p)
"rejected", p.rejected_val[]
else
"pending", nothing
end
show(io, m, @htl(
"<div style='
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: baseline;
font-size: 1rem;
background: $(
state === "rejected" ?
"linear-gradient(90deg, #ff2e2e14, transparent)" :
"unset"
);
border-radius: 7px;
'>$(display === nothing ?
@htl(
"""<code style='background: none;'>$(typestr)( $(
"<$(state)>"
) )</code>""") :
@htl("""<code style='background: none;'>$(typestr)( $(
"<$(state)>: "
)</code>$(
(
AbstractPlutoDingetjes.is_inside_pluto(io) ?
Main.PlutoRunner.embed_display :
identity
)(something(display))
)<code style='background: none;'> )</code>""")
)</div>"
))
end
@doc """
```julia
Promise{T=Any}((resolve, reject) -> begin
...
resolve(value)
end)
```
Run code asynchronously, and keep a reference to its future value.
Based on [`Promise` in JavaScript](https://javascript.info/promise-basics)!
""" Promise
end
# ╔═╡ 418f24b9-a86d-45d5-bba1-5dcd188ffafa
yay_result = Promise((resolve, reject) -> resolve("🌟 yay!"))
# ╔═╡ d8aa3fed-78f0-417a-8e47-849ec62fa056
oopsie_result = Promise((res, rej) -> rej("oops!"))
# ╔═╡ acfae6b5-947a-4648-99ba-bcd2dd3afbca
Promise((res, rej) -> rej("oops!")).then(x -> x + 10).then(x -> x / 100)
# ╔═╡ 66b2b18a-2afe-4607-8982-647681ff9816
Promise((res, rej) -> rej("oops!")).then(x -> x + 10).catch(x -> 123)
# ╔═╡ 959d2e3e-1ef6-4a97-a748-31b0b5ece938
Promise{String}((res,rej) -> res("asdf"))
# ╔═╡ f0b73769-dea5-4dfa-8a39-ebf6584abbf5
Core.Compiler.return_type(fetch, (Promise{String},))
# ╔═╡ 9d9179de-19b1-4f40-b816-454a8c071c3d
Promise{String}((res,rej) -> res(12341234))
# ╔═╡ db33260f-e3c9-4184-a4aa-1836e5f4201e
typeof(
Promise{String}((res,rej) -> res("asdf")).then(first)
)
# ╔═╡ 06a3eb82-0ffd-4c89-8161-d0f385c2a32e
md"""
# `async`/`await`
"""
# ╔═╡ 939c6e86-ded8-4b15-890b-80207e8d692a
macro await(expr)
:(Base.fetch($(esc(expr))))
end
# ╔═╡ 5a5f26dd-f0df-4dc7-be26-6bb23cc27fb2
function wrap_output_type_in_promise(e)
if Meta.isexpr(e, :where)
Expr(e.head, wrap_output_type_in_promise(e.args[1]), e.args[2:end]...)
elseif Meta.isexpr(e, Symbol("::"), 2)
Expr(Symbol("::"), e.args[1], Expr(:curly, Promise, e.args[2]))
else
e
end
end
# ╔═╡ 09661381-baec-4e1a-8f4f-dac7aeb4ea3c
function async_promise_core(expr)
Promise
cleanup_backtrace
quote
Promise() do res, rej
task = Task() do
try
value = $(esc(expr))
res(value)
catch e
rej(cleanup_backtrace(CapturedException(e, catch_backtrace())))
end
end
schedule(task)
end
end
end
# ╔═╡ 70ff0b9b-3aa2-4f3f-ab1b-b0a7072e7ffd
function async_promise(expr)
if Meta.isexpr(expr, :block, 1) ||
(Meta.isexpr(expr, :block, 2) && expr.args[1] isa LineNumberNode)
Expr(:block,
expr.args[1:end-1]...,
async_promise(expr.args[end])
)
else
if Meta.isexpr(expr, :(->)) || Meta.isexpr(expr, :function)
# TODO: we could automatically get the promise resolve type?
if length(expr.args) == 1
expr
elseif length(expr.args) == 2
Expr(
expr.head,
esc(wrap_output_type_in_promise(expr.args[1])),
async_promise_core(expr.args[2]),
)
else
throw(ArgumentError("Don't know what kind of function definition this is.\n\n$(expr)"))
end
else
async_promise_core(expr)
end
end
end
# ╔═╡ a854b9e6-1a82-401e-90d5-f05ffaadae61
macro async_promise(expr)
async_promise(expr)
end
# ╔═╡ 7aef0b5c-dd09-47d3-a08f-81cce84d7ca6
@skip_as_script download_result = @async_promise begin
# This will download the data,
# write the result to a file,
# and return the filename.
Downloads.download("https://api.github.com/users/$(username)")
end
# ╔═╡ d22278fd-33cb-4dad-ad5f-d6d067c33403
@skip_as_script download_result
# ╔═╡ f9fad7ff-cf6f-43eb-83bd-efc0cb6cde65
@skip_as_script @await download_result
# ╔═╡ 42c6edee-d43a-40cd-af4f-3d572a6b5e9a
@skip_as_script download_result.then(
filename -> read(filename, String)
).then(
str -> JSON.parse(str)
)
# ╔═╡ 34364f4d-e257-4c22-84ee-d8786a2c377c
@skip_as_script bad_result = download_result.then(d -> sqrt(-1))
# ╔═╡ cfcbf74b-08fe-4be2-a7ac-2a0272a41922
@skip_as_script @await bad_result
# ╔═╡ 2d116910-eb94-49b0-9e51-03fc9e57aebb
macroexpand(@__MODULE__, :(@async_promise function f(a::A, b::B)::C
sleep(1)
123
end), recursive=false) |> Base.remove_linenums!
# ╔═╡ 2f7147f0-6b4a-4364-8aab-07f8e150b720
macroexpand(@__MODULE__, :(@async_promise (a,b) -> begin
sleep(1)
123
end), recursive=false) |> Base.remove_linenums!
# ╔═╡ 4568aa57-7440-41a0-9eba-4050ce778ebd
macroexpand(@__MODULE__, :(@async_promise begin
sleep(1)
123
end), recursive=false) |> Base.remove_linenums!
# ╔═╡ 8e13e697-e29a-473a-ac11-30e0199be5bb
md"""
### Behaviour
"""
# ╔═╡ b9368cf7-cbcd-4b54-9390-78e8c88f064c
# ╔═╡ 26f26b5d-7352-421c-a20b-9ec37dfe3eb6
# ╔═╡ a8a07647-2b61-4401-a04d-0921a6bcec76
# ╔═╡ 51ef3992-d6a7-4b46-970c-6b075d14fb71
# ╔═╡ 5d943937-2271-431c-8fc0-4f963aa4dda0
# ╔═╡ 40c9f96a-41e9-496a-b174-490b72927626
# let
# c = Channel(1)
# p = Promise((r,_) -> r(take!(c)))
# sleep(.1)
# @assert !isready(p)
# xs = []
# ps = map(1:20) do i
# p.then(v -> push!(xs, i))
# end
# put!(c, 123)
# wait(p)
# wait.(ps)
# @test xs == 1:20
# end
# ╔═╡ 3f97f5e7-208a-44dc-9726-1923fd8c824b
# ╔═╡ c68ab4c1-6384-4802-a9a6-697a63d3488e
macro testawait(x)
# fetch = Base.fetch
fetch = Expr(:., :Base, QuoteNode(:fetch))
wrap(x::Expr) = Expr(:call, fetch, x)
wrap(x::Any) = x
e = if Meta.isexpr(x, :call, 3) && (
x.args[1] === :(==) || x.args[1] === :(===)
)
Expr(:call, x.args[1],
wrap(x.args[2]),
wrap(x.args[3]),
)
else
error("Don't know how to await this expression.")
end
:(@test $(e))
end
# ╔═╡ 8ac00844-24e5-416d-aa31-28242e4ee6a3
@testawait nothing === Promise() do res, rej
sleep(.05)
sqrt(-1)
res(5)
end.then(x -> x* 10).catch(e -> nothing)
# ╔═╡ 9ee2e123-7a24-46b2-becf-2d011abdcb19
md"""
### Types
"""
# ╔═╡ 58533024-ea65-4bce-b32a-727a804d1f4d
@test promote_type(Promise{Int64},Promise{Float64}) === Promise{Float64}
# ╔═╡ 5447d12d-7aa5-47f3-bf04-2516a8974bb9
md"""
### Benchmark
(Could be better 😅)
"""
# ╔═╡ 55fb60c1-b48b-4f0a-a24c-dcc2d7f0af4b
Promise((res,rej) -> res(-50)).then(sqrt)
# ╔═╡ 10bfce78-782d-49a1-9fc8-6b2ac5d16831
Promise((res,rej) -> res(-50)).then(sqrt).catch(e -> 0)
# ╔═╡ 5bb55103-bd26-4f30-bed6-026b003617b7
@benchmark(
fetch(Promise((res,rej) -> res(-50)).then(sqrt).catch(e -> 0)),
seconds=3
)
# ╔═╡ 74896c89-d332-4f99-aeda-d429fa4ece2e
let
c = Channel(1)
put!(c, 1)
isready(c)
# @benchmark isready($c) || wait($c)
end
# ╔═╡ 287f91b6-a602-457a-b32b-e0c22f15d514
@benchmark(
fetch(Promise((res,rej) -> res(50)).then(sqrt).catch(e -> 0).then(sqrt)),
seconds=3
)
# ╔═╡ fb11d74a-d13c-4459-a4b5-dbc23174dfd4
@benchmark(
fetch(Promise((res,rej) -> res(50)).then(sqrt).then(sqrt)),
seconds=3
)
# ╔═╡ ef2a034d-5e33-46c2-a627-0721170b5b34
@benchmark(
fetch(Promise{Int64}((res,rej) -> res(50)).then(sqrt).then(sqrt)),
seconds=3
)
# ╔═╡ 788a27b3-aab0-42cc-8197-3cc5b3b875d1
# @benchmark(
# let
# c = Channel(1)
# for x in 1:100
# t = @async begin
# take!(c)
# end
# put!(c, nothing)
# end
# end,
# seconds=3
# )
# ╔═╡ 836bf28f-caa5-44e0-ac8c-44a722a9063b
# @benchmark(
# let
# a = fetch(@async 50)
# for x in 1:100
# a = fetch(@async sqrt(a))
# end
# end,
# seconds=3
# )
# ╔═╡ 371cede0-6f01-496a-8059-e110dbfc8d05
# @benchmark(
# sqrt(sqrt(50)),
# seconds=3
# )
# ╔═╡ eb4e90d9-0e21-4f06-842d-4260f074f097
md"""
# Wait for settled
"""
# ╔═╡ 8f37aee7-b5e0-44e3-a6d0-fbbb5b88f3ef
md"""
## `Resolved{T}` and `Rejected{T}` types
"""
# ╔═╡ 7c9b31e6-cb90-4734-bf7b-6c7f0337ac62
begin
abstract type PromiseSettledResult{T} end
Base.promote_rule(
::Type{<:PromiseSettledResult{T}},
::Type{<:PromiseSettledResult{S}}
) where {T,S} = PromiseSettledResult{promote_type(T,S)}
PromiseSettledResult
end
# ╔═╡ 27876191-a023-49e9-bb3a-d3b3f10090d8
begin
struct Resolved{T} <: PromiseSettledResult{T}
value::T
end
struct Rejected{T} <: PromiseSettledResult{T}
value::T
end
for RT in subtypes(PromiseSettledResult)
@eval Base.only(a::$RT) = a.value
@eval Base.:(==)(a::$RT, b::$RT) = a.value == b.value
@eval Base.hash(a::$RT) = hash(a.value, hash($RT))
@eval Base.promote_rule(
t1::Type{$RT{T}},
t2::Type{$RT{S}}
) where {T,S} = $RT{promote_type(T,S)}
@eval function Base.convert(
::Type{<:$PromiseSettledResult{T}},
r::$RT{S}
) where {T,S}
$RT{T}(convert(T, r.value))
end
end
md"""
```julia
struct Resolved{T} <: PromiseSettledResult{T}
value::T
end
struct Rejected{T} <: PromiseSettledResult{T}
value::T
end
```
"""
end
# ╔═╡ a5b9e007-0282-4eb6-88dd-34855fe42fa4
function await_settled(p::Promise{T})::PromiseSettledResult where T
wait(p.done)
isresolved(p) ?
Resolved{T}(something(p.resolved_val[])) :
Rejected(something(p.rejected_val[]))
end
# ╔═╡ cb47c8c9-2872-4e35-9939-f953319e1acb
@test Promise{Int64}() do res, rej
res(1)
res(2)
end |> await_settled === Resolved(1)
# ╔═╡ 6a84cdd0-f57e-4535-bc16-24bc40018033
@test Promise{Int64}() do res, rej
rej("asdf")
rej("wow")
end |> await_settled === Rejected("asdf")
# ╔═╡ a0534c86-5cd6-456a-93a6-19292b5879d6
@test Promise{Int64}() do res, rej
rej("asdf")
sqrt(-1)
rej("wow")
end |> await_settled === Rejected("asdf")
# ╔═╡ be56fd49-7898-4171-8837-8c1b251cdeba
@test Promise{Int64}() do res, rej
sqrt(-1)
rej("asdf")
rej("wow")
end |> await_settled isa Rejected{CapturedException}
# ╔═╡ 6bb08e1c-bfe9-40c7-92b5-5c71aba040dd
@test Promise{Int64}() do res, rej
res(1)
sqrt(-1)
rej("asdf")
end |> await_settled === Resolved(1)
# ╔═╡ 9aa052ef-5f60-4935-94d1-a4cbc5096d46
@skip_as_script let
p1 = Promise{Int64}() do res, rej
res(1)
end
p2 = Promise{Int64}() do res, rej
p1.then(res)
await_settled(p1)
yield()
res(-100)
end
@test await_settled(p2) === Resolved(1)
end
# ╔═╡ 2b6e41af-c9e9-4774-a6f5-51c301705a10
@skip_as_script let
p1 = Promise{Int64}() do res, rej
rej(-1)
end
p2 = Promise{Int64}() do res, rej
p1.catch(res)
await_settled(p1)
yield()
res(-100)
end
@test await_settled(p2) === Resolved(-1)
end
# ╔═╡ 1ef3378e-62ac-463b-b8c0-dfb6f46f956b
@skip_as_script let
p1 = Promise{Int64}() do res, rej
sqrt(-1)
end
p2 = Promise{Any}() do res, rej
p1.catch(res)
await_settled(p1)
yield()
res(2)
end
@test fetch(p2) isa CapturedException
end
# ╔═╡ 5869262c-40fe-4752-856d-1da536e3e11a
@skip_as_script let
p1 = Promise{Int64}() do res, rej
sqrt(-1)
end
p2 = Promise{Any}() do res, rej
p1.catch(res)
await_settled(p1)
yield()
res(-100)
end
@test fetch(p2) isa CapturedException
end
# ╔═╡ 3cb7964a-45bb-471e-9fca-c390e06b0fee
@test Promise{Int64}() do res, rej
res("asdf")
end |> await_settled isa Rejected{CapturedException}
# ╔═╡ 9e27473e-91b3-4261-8033-5295d4a94426
@test Promise{Int64}() do res, rej
@async res("asdf")
end |> await_settled isa Rejected{CapturedException}
# ╔═╡ 4d661d30-6522-4e7d-895a-786d2d776809
@test await_settled(Promise{String}((r,_) -> (sleep(.1); r("asdf")))) ===
Resolved{String}("asdf")
# ╔═╡ fa4d6805-8b15-4c24-991c-6762d2701932
@test await_settled(Promise{Int64}((res,rej) -> rej("asdf"))) ===
Rejected{String}("asdf")
# ╔═╡ 56e274e8-7523-45f1-bd44-5ef71d2feaf2
md"""
### Promotion, conversion
"""
# ╔═╡ 75de613a-3eb8-49e8-9f71-fc55b76cef00
@test promote_rule(Resolved{Int64}, Rejected{Float64}) ==
PromiseSettledResult{Float64}
# ╔═╡ 497a01eb-7cf9-47b9-95bf-75f59829be36
@test promote_rule(PromiseSettledResult{Int64}, Resolved{Float64}) ==
PromiseSettledResult{Float64}
# ╔═╡ c7ec7091-a9b3-46c8-8eaf-222b5eb7ebc2
@test promote_rule(Resolved{Int64}, Resolved{Float64}) == Resolved{Float64}
# ╔═╡ 44769580-1983-45ac-b1d5-d5ddb252f7bf
@test convert(PromiseSettledResult{Float64}, Resolved(1)) === Resolved(1.0)
# ╔═╡ 3b11ace6-cdf7-4c90-a96c-f804c3cb4e2f
md"""
### Equality, hash
"""
# ╔═╡ c9bc257b-b204-4019-ab65-9d9489cee16d
@test Resolved(1) == Resolved(1.0)
# ╔═╡ ee4c0c55-bf1d-42c8-8de1-350dd17dff7d
@test Rejected(1) == Rejected(1.0)
# ╔═╡ cc244956-78e0-4804-bc14-91c629bdf28f
@test hash(Resolved(1)) == hash(Resolved(1.0))
# ╔═╡ aa22fed7-bb22-4d52-9e64-3f4a27597f93
@test hash(Rejected(1)) == hash(Rejected(1.0))
# ╔═╡ 02edf8aa-10b3-4da9-a097-3b9dc9a7302d
@test hash(Resolved(1)) != hash(Rejected(1.0))
# ╔═╡ a0c7275b-8fcb-4c0b-b724-aa29f0b878e8
md"""
# Combining promises
We also have ports of the JavaScript functions: `Promise.all`, `Promise.any` and `Promise.reject`.
"""
# ╔═╡ 0dcba3ea-1884-4136-b9a6-42b4cbdf0c50
fetch_all(ps) = fetch.(ps)
# ╔═╡ e36ae108-ab09-4e9c-a6a1-9e596408fda0
fetch_all(ps::AbstractSet) = Set(fetch(p) for p in ps)
# ╔═╡ a0a5f687-56a6-4bc0-9e0a-6d22d0d2de47
"""
```julia
all(promises::AbstractVector{Promise})::Promise
all(promises::AbstractSet{Promise, ...})::Promise
all(promises::Tuple{Promise, Promise, ...})::Promise
```
Create a new Promise that waits for all given `promises` to resolved, and then resolves to a single vector, tuple or set with all the values.
If any of the `promises` rejects, the new Promise will also reject.
See also:
- [`any`](@ref), which only rejects if every one of the `promises` rejects.
- [`race`](@ref), which rejects immediately if one of the `promises` rejects.
"""
function promise_all(ps)
T = Core.Compiler.return_type(fetch_all, (typeof(ps),))
Promise{T}() do res, rej