Skip to content

Commit

Permalink
feat: remove tasker dependency
Browse files Browse the repository at this point in the history
in favour of native timeouts
  • Loading branch information
stakach committed Jun 21, 2021
1 parent fd08e20 commit 271f146
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 14 deletions.
7 changes: 1 addition & 6 deletions shard.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
name: promise
version: 2.2.2
version: 2.2.3
crystal: ">= 0.36.1"

dependencies:
tasker:
github: spider-gazelle/tasker
version: ~> 2.0

development_dependencies:
ameba:
github: veelenga/ameba
10 changes: 8 additions & 2 deletions spec/promise_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,10 @@ describe Promise do
p1 = Promise.new(Symbol)
p2 = Promise.new(String)
spawn(same_thread: true) { p2.resolve("testing") }
delay(0.002) { p1.resolve(:foo) }
spawn do
sleep 0.002
p1.resolve(:foo)
end
val = Promise.race(p1, p2).get
val.should eq "testing"
end
Expand All @@ -508,7 +511,10 @@ describe Promise do
p1 = Promise.new(Symbol)
p2 = Promise.new(String)
spawn(same_thread: true) { p2.reject("testing") }
delay(0.002) { p1.resolve(:foo) }
spawn do
sleep 0.002
p1.resolve(:foo)
end

begin
val = Promise.race(p1, p2).get
Expand Down
19 changes: 13 additions & 6 deletions src/promise.cr
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
require "tasker"

abstract class Promise
class Generic(Output)
macro get_type_var
Expand All @@ -20,12 +18,22 @@ abstract class Promise
class Timeout < Exception
end

def self.timeout(promise : Promise, time : Time::Span)
cancel = Channel(Bool).new(1)
promise.then { cancel.send(true) }

select
when cancel.receive
when timeout(time)
promise.reject(::Promise::Timeout.new("operation timeout"))
end
end

macro new(type, timeout = nil)
{% if timeout %}
begin
%promise = ::Promise::DeferredPromise({{type.id}}).new
%task = Tasker.in({{timeout}}) { %promise.reject(::Promise::Timeout.new("operation timeout")) }
%promise.finally { %task.cancel }
spawn { ::Promise.timeout(%promise, {{timeout}}) }
%promise
end
{% else %}
Expand All @@ -42,8 +50,7 @@ abstract class Promise
}.execute!

{% if timeout %}
%task = Tasker.in({{timeout}}) { %promise.reject(::Promise::Timeout.new("operation timeout")) }
%promise.finally { |err| %task.cancel unless err.is_a?(::Promise::Timeout) }
spawn { ::Promise.timeout(%promise, {{timeout}}) }
%promise
{% end %}

Expand Down

0 comments on commit 271f146

Please sign in to comment.