Last active
July 25, 2023 00:50
-
-
Save hwahyang1/b49d256717a0aeb2a9413092e9aabf4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
/// <summary> | |
/// TaskCompletionSource를 이용한 비동기 반환 클래스 입니다. | |
/// JavaScript의 Promise를 모방한 클래스입니다. | |
/// </summary> | |
/// <remarks> | |
/// JavaScript에서의 Promise (MDN Docs): | |
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise | |
/// </remarks> | |
/// <example> | |
/// https://gist.github.com/hwahyang1/b49d256717a0aeb2a9413092e9aabf4e | |
/// </example> | |
public class Promise<T> | |
{ | |
private TaskCompletionSource<T> taskCompletionSource; | |
public Promise() | |
{ | |
taskCompletionSource = new TaskCompletionSource<T>(); | |
} | |
public void Resolve(T result) | |
{ | |
taskCompletionSource.SetResult(result); | |
} | |
public void Reject(string message) | |
{ | |
taskCompletionSource.SetException(new Exception(message)); | |
} | |
public void Reject(Exception e) | |
{ | |
taskCompletionSource.SetException(e); | |
} | |
public Task<T> Fetch => taskCompletionSource.Task; | |
} | |
public class MyClass | |
{ | |
public Promise<int> PerformAsyncOperation() | |
{ | |
// Return Type 지정 | |
Promise<int> promise = new Promise<int>(); | |
Task.Delay(5000).ContinueWith(_ => | |
{ | |
Random random = new Random(); | |
if (random.Next(0, 2) == 0) | |
{ | |
int result = random.Next(1, 101); | |
// Return Value | |
promise.Resolve(result); | |
} | |
else | |
{ | |
// Throw Error | |
promise.Reject("Failed to perform the async operation."); | |
// OR, | |
//promise.Reject(new Exception("Failed to perform the async operation.")); | |
} | |
}); | |
return promise; | |
} | |
} | |
public class Program | |
{ | |
public static async Task Main(string[] args) | |
{ | |
MyClass myClass = new MyClass(); | |
Promise<int> promise = myClass.PerformAsyncOperation(); | |
try | |
{ | |
int result = await promise.Fetch; | |
Console.WriteLine("Async operation result: " + result); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine("Async operation failed: " + e.Message); | |
} | |
// OR, | |
try | |
{ | |
int result = await myClass.PerformAsyncOperation().Fetch; | |
Console.WriteLine("Async operation result: " + result); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine("Async operation failed: " + e.Message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment