diff --git a/lib/init.lua b/lib/init.lua index 41d1e64..bf0eb04 100644 --- a/lib/init.lua +++ b/lib/init.lua @@ -1893,30 +1893,47 @@ function Promise.prototype:_reject(...) self:_finalize() end ---[[ - Calls any :finally handlers. We need this to be a separate method and - queue because we must call all of the finally callbacks upon a success, - failure, *and* cancellation. -]] -function Promise.prototype:_finalize() - for _, callback in ipairs(self._queuedFinally) do - -- Purposefully not passing values to callbacks here, as it could be the - -- resolved values, or rejected errors. If the developer needs the values, - -- they should use :andThen or :catch explicitly. - coroutine.wrap(callback)(self._status) +do + local threadsToClose = {} + local closingTask = nil + + local function closeThreads() + closingTask = nil + local threads = threadsToClose + threadsToClose = {} + for _, thread in threads do + coroutine.close(thread) + end end - self._queuedFinally = nil - self._queuedReject = nil - self._queuedResolve = nil + --[[ + Calls any :finally handlers. We need this to be a separate method and + queue because we must call all of the finally callbacks upon a success, + failure, *and* cancellation. + ]] + function Promise.prototype:_finalize() + for _, callback in ipairs(self._queuedFinally) do + -- Purposefully not passing values to callbacks here, as it could be the + -- resolved values, or rejected errors. If the developer needs the values, + -- they should use :andThen or :catch explicitly. + coroutine.wrap(callback)(self._status) + end + + self._queuedFinally = nil + self._queuedReject = nil + self._queuedResolve = nil - -- Clear references to other Promises to allow gc - if not Promise.TEST then - self._parent = nil - self._consumers = nil - end + -- Clear references to other Promises to allow gc + if not Promise.TEST then + self._parent = nil + self._consumers = nil + end - task.defer(coroutine.close, self._thread) + table.insert(threadsToClose, self._thread) + if not closingTask then + closingTask = task.defer(closeThreads) + end + end end --[=[ diff --git a/rotriever.toml b/rotriever.toml index a1f1451..1cb66d0 100644 --- a/rotriever.toml +++ b/rotriever.toml @@ -1,6 +1,6 @@ [package] name = "Promise" -version = "3.5.0" +version = "3.5.1" authors = ["evaera"] license = "MIT" content_root = "lib"