I am using C# Promises library for an Unity project, and I want to call a block of promise code indefinite times. Each time the promise is resolved it should decide whether it should be called again or not. I found this JavaScript solution for ES6 in the thread JavaScript ES6 promise for loop.
// JavaScript: Function calling itself upon resolution
(function loop(i) {
if (i < 10) new Promise((resolve, reject) => {
setTimeout( () => {
console.log(i);
resolve();
}, Math.random() * 1000);
}).then(loop.bind(null, i+1));
})(0);
Could you help me to port this idea into C#?
What I am currently doing is forming a long sequence of promises using Then()
in a for
loop, and rejecting when I want to exit. But that is a weak solution. Instead, I want to only consider about the next iteration when the current promise is resolved.
// C#: Forming the sequence before execution
var p = Promise.Resolved();
for (var i = 0; i < 100; i++)
{
p = p.Then(outcome =>
{
if (shouldContinue)
{
// return a new Promise
}
else
{
// return Promise.Reject()
}
});
}
Edit:
Please take a look at my answer below for the PromiseLooper
class.