util.async: Factor out thread check into a function
authorKim Alvefur <zash@zash.se>
Tue, 21 Nov 2017 21:48:14 +0100
changeset 8410 f652e1ea2f69
parent 8409 e39edc6d1523
child 8411 b751bee6a829
util.async: Factor out thread check into a function
util/async.lua
--- a/util/async.lua	Mon Nov 20 02:22:09 2017 +0100
+++ b/util/async.lua	Tue Nov 21 21:48:14 2017 +0100
@@ -1,5 +1,13 @@
 local log = require "util.logger".init("util.async");
 
+local function checkthread()
+	local thread = coroutine.running();
+	if not thread then
+		error("Not running in an async context, see https://prosody.im/doc/developers/util/async");
+	end
+	return thread;
+end
+
 local function runner_continue(thread)
 	-- ASSUMPTION: runner is in 'waiting' state (but we don't have the runner to know for sure)
 	if coroutine.status(thread) ~= "suspended" then -- This should suffice
@@ -25,10 +33,7 @@
 end
 
 local function waiter(num)
-	local thread = coroutine.running();
-	if not thread then
-		error("Not running in an async context, see https://prosody.im/doc/developers/util/async");
-	end
+	local thread = checkthread();
 	num = num or 1;
 	local waiting;
 	return function ()
@@ -48,10 +53,7 @@
 local function guarder()
 	local guards = {};
 	return function (id, func)
-		local thread = coroutine.running();
-		if not thread then
-			error("Not running in an async context, see https://prosody.im/doc/developers/util/async");
-		end
+		local thread = checkthread();
 		local guard = guards[id];
 		if not guard then
 			guard = {};