I’ve been wondering if it’s possible to use promises over while loops. For example, as for my case, I want to create a simple countdown system except with promises instead of while loops. Tried a few ways like creating a function for round and intermission where the promises are returned and then resolve them but uhh, my attempt didn’t work at all. Need some code suggestions.
Here's a copy-paste for the countdown
local function Countdown(From: number)
for i = From, 0, -1 do
print(i)
task.wait(1)
end
end
Here's the round initiating function
local function InitiateRound()
local RoundTime = 5
local IntermissionTime = 5
local function DoIntermission()
return Promise.Resolve(function()
Countdown(IntermissionTime)
end)
end
local function DoRound()
return Promise.Resolve(function()
Countdown(RoundTime)
end)
end
local function RoundLoop()
local RoundPromise = nil
local IntermissionPromise = DoIntermission()
IntermissionPromise:Await()
IntermissionPromise:Finally(function()
print("intermission ended")
if RoundPromise == nil then
RoundPromise = DoRound()
end
RoundPromise:Await()
RoundPromise:Finally(function()
RoundLoop()
end)
end)
end
RoundLoop()
end
I’m not sure why you want to utilize promises as a countdown, but I believe that this is what you want to accomplish. You might be able to use the clock that is built into the module you are using. Hope this was helpful.
local Red = require(game:GetService("ReplicatedStorage").Red)
function countdown(a)
return Red.Promise.new(function(res, rej)
print(a)
a -= 1
if a > 0 then
task.wait(1)
countdown(a).Then(res)
else
-- What you want to execute when the countdown is at 0
print(`Finished count: {a}`)
end
end)
end
local counter = countdown(10)
counter.Then(function(msg)
print(msg)
end)
While loops feel like an obstacle to running the scripts to me. Of course, you can use task.spawn or coroutine.wrap for asynchronous code, but I’d prefer promises over that.
I’ll try the code you provided, thanks for the idea.
No issue! Here is a code sample if you still don’t get it.
local Red = require(game:GetService("ReplicatedStorage").Red)
local Intermission, Round = {
Name = "Intermission",
Time = 5
}, {
Name = "Round",
Time = 5
}
function Match(Current)
local Duration = Current.Time
return Red.Promise.new(function(Response, Reject)
print(Duration)
Duration -= 1
if Duration > 0 then
task.wait(1)
Match({
Name = Current.Name,
Time = Duration
}).Then(Response)
else
task.wait(1)
if Current.Name == "Intermission" then
print('Intermission ended')
Match(Round).Then(Response)
end
if Current.Name == "Round" then
print('Intermission started')
Match(Intermission).Then(Response)
end
end
end)
end
Match(Intermission)