-So i’m learning about Promise module and keep getting confused when learn new things,there are 2 functions that i want to understand:
1.Promise.fold()
2.Promise.race()
What are these functions do?
-I keep trying to ask people on discord,but there are no replies yet.
-I keep trying to understand it,but i can’t.
local basket = {"blueberry", "melon", "pear", "melon"}
Promise.fold(basket, function(cost, fruit)
if fruit == "blueberry" then
return cost -- blueberries are free!
else
-- call a function that returns a promise with the fruit price
return fetchPrice(fruit):andThen(function(fruitCost)
return cost + fruitCost
end)
end
end, 0)
local function async1()
return Promise.async(function(resolve, reject)
local ok, value = async2():await()
if not ok then
return reject(value)
end
resolve(value + 1)
end)
end
Please explain me about these two functions,Thanks for reading this post!
Bumping cause I also need some help and couldn´t find any relating to the same issue. (And for future peasants who also need help).
local function awaitSelection()
local p1 = Promise.new(function(resolve,reject,onCancel)
local con = confirmButton.MouseButton1Click:Connect(function() resolve(confirmButton) end)
onCancel(function() con:Disconnect() end)
end)
local p2 = Promise.new(function(resolve,reject,onCancel)
local con = cancelButton.MouseButton1Click:Connect(function() resolve(cancelButton) end)
onCancel(function() con:Disconnect() end)
end)
Promise.any({p1,p2}):andThen(warn,warn):await()
end
I am trying to use promise.any or promise.race, and this code returns me the button pressed. But I thought this method is supposed to cancel the promises after one wins the race condition.
As soon as one Promises resolves, all other pending Promises are cancelled if they have no other consumers.
EDIT: im just dumb and this works (i was looping this function by accident)
Promise.fold is just a reduce function, where there is an accumulator set to the initial value, a function is called for each element, and the accumulator is changed to the return value of that function. It’s helpful, for example, easily getting the sum of all numbers in a table:
Promise.fold({1, 6, 3, 7}, function(a, n) return a + n end, 0) -- 17
Promise.race runs through every promise specified, and returns the result of the fastest promise, reject or resolve.