Real-Serious-Games / C-Sharp-Promise

Promises library for C# for management of asynchronous operations.
MIT License
1.19k stars 149 forks source link

Need implicit casts between Promise<object> and Promise and interfaces #93

Closed ericnewton76 closed 4 years ago

ericnewton76 commented 5 years ago

Need some implicit casts for T=object scenarios. I keep running into odd compiler errors of not able to convert from Promise to Promise which returns an object... lol

I'd like to start the discussion at least. I'm trying ponder this for a bit, as I'm trying to use this library in a non-unity scenario, but realistically I really love the idea. I believe JS got async programming correct with Promises, and C# team got async wrong with their Task async await mentality. (Granted the await is coming to JS which is good too)

ericnewton76 commented 5 years ago

Just to clarify after thinking about this.

All Promises should still shuttle around an object reference, and that object ref can be null.

So a Then((x) => { Assert.That(x==null) }) on a Promise<object> cast to a Promise. This should work fine, given the following:

var Promise1 = new Promise((resolve,reject) => { resolve(); });
var Promise2 = new Promise<string>((resolve,reject) => { resolve("A"); });
var Promise3 = new Promise<int>((resolve,reject) => { resolve(1); });

Promise.All(Promise1, Promise2, Promise3) 
//Could force this to be Promise<object>.All but realistically that should be the default I think
//but even Promise<object>.All doesnt work because Promise1 cant convert to IPromise<object>
.Then(results => {
  Assert.That(results.ElementAt(0), Is.Null);

  Assert.That(results.ElementAt(1), Is.NotNull);
  Assert.That(results.ElementAt(1), Is.EqualTo("A"));

  Assert.That(results.ElementAt(2), Is.NotNull);
  Assert.That(results.ElementAt(2), 1);
}

Unless I'm not thinking about this correctly... lol

I will probably generate a PR for this, I worry that it'll touch every aspect of the library though.

ericnewton76 commented 5 years ago

Just a question, was there a need for the IPromise interfaces? I dont actually see a need for them.

That way, Promise.All takes Promise types instead, and the implicit casts can easily shuttle Promise to Promise due to baseclass

public static Promise Promise.All(params Promise[] promises)
ashleydavis commented 5 years ago

It doesn't feel right to me that a promise that yields no value should be able to implicitly cast to a null result.

There are two reasons for the interfaces.

  1. Having an interface allows a promise to be mocked.
  2. Having two interfaces allows you to seperate your concerns. One interface allows a promise to be awaited, the other allows a promise to be resolved.