-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.yue
426 lines (336 loc) · 12.4 KB
/
promise.yue
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
--[[
MIT License
Copyright (c) 2023-2024 Retro
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
import Error, TypeError, RuntimeError from include "error.lua"
import isfunction, istable, isstring, getmetatable, pcall, xpcall, error, ipairs from _G
import format, match from string
import create, resume, yield, running from coroutine
import remove from table
setTimeout = timer.Simple
iscallable = (obj) ->
if isfunction obj
return true
meta = getmetatable obj
return meta and meta.__call and true or false
getThenable = (obj) ->
thenFn = obj.Then or obj.next
return iscallable(thenFn) and thenFn
getAwaitable = (obj) ->
awaitable = obj.Await or obj.await
return iscallable(awaitable) and awaitable
once = ->
wasCalled = false
return (wrappedFn) ->
return (...) ->
if wasCalled then return ...
wasCalled = true
return wrappedFn(...)
class HTTPError extends Error
class PromiseError extends Error
class Promise
@VERSION: "2.1.0"
@AUTHOR: "Retro"
@URL: "https://github.com/dankmolot/gm_promise"
STATE_PENDING = 1
STATE_FULFILLED = 2
STATE_REJECTED = 3
IsPromise = (obj) -> istable(obj) and obj.__class == Promise
new: (executor) =>
@state = STATE_PENDING
@resolving = false
if iscallable executor
@resolving = true
once_wrapper = once!
onFulfill = once_wrapper (value) -> resolve( @, value )
onReject = once_wrapper (reason) -> reject( @, reason )
try executor onFulfill, onReject
catch err
onReject err
__tostring: =>
return switch @state
when STATE_PENDING
format "Promise %p { <state>: \"pending\" }", @
when STATE_FULFILLED
format "Promise %p { <state>: \"fulfilled\", <value>: %s }", @, @value
when STATE_REJECTED
format "Promise %p { <state>: \"rejected\", <reason>: %s }", @, @reason
else
format "Promise %p { <state>: \"invalid\" }", @
finalizePromiseUnsafe = (p) =>
:onFulfilled, :onRejected, :onFinally = p
switch @state
when STATE_FULFILLED
if onFulfilled then resolve( p, onFulfilled(@value) )
else resolve( p, @value )
when STATE_REJECTED
if onRejected then resolve( p, onRejected(@reason) )
else reject( p, @reason )
if onFinally
onFinally!
return
finalizePromise = (p) =>
unless success, err := try finalizePromiseUnsafe( @, p )
reject( p, err )
finalize = =>
if @state == STATE_PENDING
return
setTimeout 0, ->
queue = @queue
index = 1
while queue and queue[index]
finalizePromise( @, queue[index] )
queue[index] = nil
index += 1
fulfill = (value) =>
@state = STATE_FULFILLED
@value = value
finalize( @ )
resolveThenable = (obj, thenable) =>
once_wrapper = once!
onFulfill = once_wrapper (value) -> resolve( @, value )
onReject = once_wrapper (reason) -> reject( @, reason )
unless ok, err := try thenable( obj, onFulfill, onReject )
onReject err
resolve = (value) =>
if @state != STATE_PENDING
return
if value == @
return reject @, TypeError "Cannot resolve a promise with itself"
@resolving = true
@onFulfilled = nil
@onRejected = nil
@onFinally = nil
if IsPromise value
if value.state == STATE_PENDING
value.queue = {} unless value.queue
value.queue[] = @
else
finalizePromise( value, @ )
elseif istable value
ok, thenable = try getThenable(value)
unless ok then return reject( @, thenable )
if thenable
resolveThenable( @, value, thenable )
else
fulfill( @, value )
else
fulfill( @, value )
reject = (reason) =>
if @state != STATE_PENDING
return
@state = STATE_REJECTED
@reason = reason
finalize( @ )
Resolve = (value) => unless @resolving then resolve( @, value )
Reject = (reason) => unless @resolving then reject( @, reason )
@Resolve: (value) ->
p = Promise!
Resolve( p, value )
return p
@Reject: (reason) ->
p = Promise!
Reject( p, reason )
return p
Then = (onFulfilled, onRejected, onFinally) =>
p = Promise!
p.onFulfilled = onFulfilled if iscallable onFulfilled
p.onRejected = onRejected if iscallable onRejected
p.onFinally = onFinally if iscallable onFinally
@queue = {} unless @queue
@queue[] = p
finalize( @ )
return p
Catch = (onRejected) => return Then( @, nil, onRejected )
Finally = (onFinally) => return Then( @, nil, nil, onFinally )
CALL_STACK = {}
transformError = (err) ->
if isstring( err )
file, line, message = match( err, "^([A-Za-z0-9%-_/.]+):(%d+): (.*)" )
if file and line
err = RuntimeError( message, file, line, 4 )
if Error.is( err )
stack = err.stack
length = #stack
if length >= 2 and stack[length - 1].name == "xpcall"
stack[length - 1] = nil -- remove xpcall stack
stack[length] = nil -- remove promise wrapper stack
if #stack == 0 -- if stack is empty, remove debug information
err.fileName = nil
err.lineNumber = nil
lastStack = CALL_STACK[#CALL_STACK]
if lastStack
if #stack > 0 and not stack[#stack].name
stack[#stack].name = lastStack[1].name -- set previous stack name since it's the name of the function
-- Append previous stack to the current stack
for entry in *lastStack[2,]
stack[] = entry
if first := stack[1]
@fileName or= first.short_src
@lineNumber or= first.currentline
return err
@Async: (fn) ->
return (...) ->
p = Promise!
CALL_STACK[] = Error.captureStack() -- push stack
co = create (...) ->
success, result = xpcall( fn, transformError, ... )
if success
Resolve( p, result )
else
Reject( p, result )
CALL_STACK[#CALL_STACK] = nil -- pop stack
resume( co, ... )
return p
SafeAwait = (p) ->
co = running!
unless co
return false, PromiseError "Cannot await in main thread"
local _success, _value, waiting, stack
finish = (success, value) ->
if waiting
CALL_STACK[] = stack -- push previous stack
resume co, success, value
else
_success, _value = success, value
wait = ->
if _success != nil
return _success, _value
waiting = true
stack = remove( CALL_STACK ) -- pop current stack
return yield!
once_wrapper = once!
onResolve = once_wrapper (value) -> finish( true, value )
onReject = once_wrapper (reason) -> finish( false, reason )
if IsPromise p
switch p.state
when STATE_FULFILLED
return true, p.value
when STATE_REJECTED
return false, p.reason
else
Then( p, onResolve, onReject )
return wait!
thenable = istable(p) and getThenable(p)
if iscallable( thenable )
pcall( thenable, p, onResolve, onReject )
return wait!
return true, p
Await = (p) ->
awaitable = istable(p) and getAwaitable(p)
if awaitable and not IsPromise(p)
return awaitable(p)
ok, result = SafeAwait(p)
if ok then return result
else error result
@All: (promises) ->
p = Promise!
count = #promises
values = {}
if count == 0
Resolve( p, values )
for i, promise in ipairs promises
if IsPromise promise
promise\Then (value) ->
values[i] = value
count -= 1
if count == 0
Resolve( p, values ),
(reason) -> Reject( p, reason )
else
values[i] = promise
count -= 1
if count == 0
Resolve( p, values )
return p
@AllSettled: (promises) ->
p = Promise!
count = #promises
values = {}
if count == 0
Resolve( p, values )
for i, promise in ipairs promises
promise\Then (value) ->
values[i] = { status: "fulfilled", value: value }
count -= 1
if count == 0
Resolve( p, values ),
(reason) ->
values[i] = { status: "rejected", reason: reason }
if count == 0
Resolve( p, values )
return p
@Any: (promises) ->
p = Promise!
count = #promises
reasons = {}
if count == 0
Reject( p, PromiseError "No promises to resolve" )
for i, promise in ipairs promises
promise\Then (value) -> Resolve( p, value ),
(reason) ->
reasons[i] = reason
count -= 1
if count == 0
Resolve( p, values )
return p
@Race: (promises) ->
p = Promise!
for promise in *promises
promise\Then (value) -> Resolve( p, value ),
(reason) -> Reject( p, reason )
return p
@Delay: (time, value) ->
p = Promise!
setTimeout time, -> Resolve( p, value )
return p
@HTTP: (options) ->
p = Promise!
options.success = (code, body, headers) ->
Resolve( p, { :code, :body, :headers } )
return
options.failed = (err) ->
Reject( p, HTTPError err )
return -- for better stacktrace
unless ok := HTTP options
Reject( p, HTTPError "failed to make http request" )
return p
-- Setting locals to class
@__base.STATE_PENDING = STATE_PENDING
@__base.STATE_FULFILLED = STATE_FULFILLED
@__base.STATE_REJECTED = STATE_REJECTED
@__base.IsPromise = IsPromise
@__base.Resolve = @__base.resolve = Resolve
@__base.Reject = @__base.reject = Reject
@__base.Then = @__base.then = @__base.next = @__base.andThen = Then
@__base.Catch = @__base.catch = Catch
@__base.Finally = @__base.finally = Finally
@__base.SafeAwait = @__base.safeAwait = SafeAwait
@__base.Await = @__base.await = Await
@resolve = @Resolve
@reject = @Reject
@async = @Async
@all = @All
@allSettled = @AllSettled
@any = @Any
@race = @Race
@delay = @Delay
@http = @HTTP
@PromiseError = PromiseError
@HTTPError = HTTPError
export default Promise