tochie-facade/scenes/Sums.gd
2023-08-28 14:32:03 +05:00

92 lines
2.6 KiB
GDScript

extends Node
class Result extends Reference:
var is_ok: bool
var value = null
static func make_value(p_value):
var result := Result.new()
result.is_ok = true
result.value = p_value
return result
static func make_error(error):
var result := Result.new()
result.is_ok = false
# todo: Proper error object / convention.
result.value = [error, get_stack().slice(1, -1)]
return result
class Promise extends Reference:
var is_done: bool = false
var is_ok: bool
var value = null
signal done()
static func from(capture: GDScriptFunctionState):
var result := Promise.new()
if capture.connect("completed", result, "_result_arrived") != OK:
assert("Bruh")
return result
static func make_value(p_value):
var result := Promise.new()
result.is_done = true
result.is_ok = true
result.value = p_value
return result
static func make_error(error):
var result := Promise.new()
result.is_done = true
result.is_ok = false
result.value = [error, get_stack().slice(1, -1)]
return result
# todo: Use Error class value for erroneous state instead.
func _result_arrived(p_result) -> void:
self.is_done = true
self.is_ok = true
self.value = p_result
emit_signal("done")
static func are_promises_done(promises: Array) -> bool:
for promise in promises:
assert(promise is Promise)
if not promise.is_done:
return false
return true
static func are_promises_ok(promises: Array) -> bool:
for promise in promises:
assert(promise is Promise)
assert(promise.is_done)
if not promise.is_ok:
return false
return true
static func collect_promise_values(promises: Array) -> Array:
var result := Array()
for promise in promises:
assert(promise is Promise)
assert(promise.is_done)
# todo: Don't do this.
if promise.value is Result:
assert(promise.value.is_ok)
result.push_back(promise.value.value)
else: result.push_back(promise.value)
return result
static func collect_promise_errors(promises: Array) -> Array:
var result := Array()
for promise in promises:
assert(promise is Promise)
assert(promise.is_done)
if not promise.is_ok:
result.push_back(promise.value)
# todo: Don't do this.
elif promise.value is Result and not promise.value.is_ok:
result.push_back(promise.value.value)
return result