Changeset

8648:ca710a71d730

util.async: Add ready() to check whether running in async context
author Matthew Wild <mwild1@gmail.com>
date Thu, 22 Mar 2018 07:46:23 +0000
parents 8647:638ff2ad98e6
children 8649:9246f64d6f1e
files spec/util_async_spec.lua util/async.lua
diffstat 2 files changed, 19 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/spec/util_async_spec.lua	Wed Mar 21 17:03:13 2018 +0100
+++ b/spec/util_async_spec.lua	Thu Mar 22 07:46:23 2018 +0000
@@ -579,4 +579,18 @@
 			assert.spy(r.watchers.ready).was_not.called();
 		end);
 	end);
+
+	describe("#ready()", function ()
+		it("should return false outside an async context", function ()
+			assert.falsy(async.ready());
+		end);
+		it("should return true inside an async context", function ()
+			local r = new(function ()
+				assert.truthy(async.ready());
+			end);
+			r:run(true);
+			assert.spy(r.func).was.called();
+			assert.spy(r.watchers.error).was_not.called();
+		end);
+	end);
 end);
--- a/util/async.lua	Wed Mar 21 17:03:13 2018 +0100
+++ b/util/async.lua	Thu Mar 22 07:46:23 2018 +0000
@@ -215,4 +215,8 @@
 	return log(level, "[runner %s] "..fmt, self.id, ...);
 end
 
-return { waiter = waiter, guarder = guarder, runner = runner };
+local function ready()
+	return pcall(checkthread);
+end
+
+return { ready = ready, waiter = waiter, guarder = guarder, runner = runner };