stick-the-quick/util/Promise.gd

46 lines
1.0 KiB
GDScript

class_name Promise extends Object
signal _sig_finished(result: Variant)
var _finished := false
var _result: Variant = null
func is_finished() -> bool:
return _finished
func get_result() -> Variant:
return _result
func join() -> Variant:
if not _finished:
await _sig_finished
return _result
func _init(arg: Variant) -> void:
var thunk: Callable
if arg is Callable:
thunk = arg
elif arg is Array:
thunk = func():
var subtasks: Array[Promise] = []
var subtask_results: Array = []
for subthunk in arg:
subtasks.push_back(Promise.new(subthunk))
while not subtasks.is_empty():
subtask_results.push_front(await subtasks.pop_back().join())
return subtask_results
elif arg is Promise:
thunk = func(): return await arg.join()
elif arg is Signal:
thunk = func(): return await arg
else:
thunk = func(): return arg
var wrapper := func():
_result = await thunk.call()
_finished = true
_sig_finished.emit(_result)
wrapper.call()
static func dummy() -> Promise:
return Promise.new(null)