| | 1 | | using System; |
| | 2 | | using UnityEngine; |
| | 3 | |
|
| | 4 | | namespace DCL.Helpers |
| | 5 | | { |
| | 6 | | public class Promise<T> : CustomYieldInstruction, IDisposable |
| | 7 | | { |
| | 8 | | private bool resolved = false; |
| | 9 | | private bool failed = false; |
| | 10 | |
|
| | 11 | | private Action<T> onSuccess; |
| | 12 | | private Action<string> onError; |
| | 13 | |
|
| 123630 | 14 | | public override bool keepWaiting => !resolved; |
| 0 | 15 | | public T value { private set; get; } |
| 0 | 16 | | public string error { private set; get; } |
| | 17 | |
|
| | 18 | | public void Resolve(T result) |
| | 19 | | { |
| 903 | 20 | | failed = false; |
| 903 | 21 | | resolved = true; |
| 903 | 22 | | value = result; |
| 903 | 23 | | error = null; |
| 903 | 24 | | onSuccess?.Invoke(result); |
| 20 | 25 | | } |
| | 26 | |
|
| | 27 | | public void Reject(string errorMessage) |
| | 28 | | { |
| 3 | 29 | | failed = true; |
| 3 | 30 | | resolved = true; |
| 3 | 31 | | error = errorMessage; |
| 3 | 32 | | onError?.Invoke(error); |
| 0 | 33 | | } |
| | 34 | |
|
| | 35 | | public Promise<T> Then(Action<T> successCallback) |
| | 36 | | { |
| 730 | 37 | | if (!resolved) |
| | 38 | | { |
| 417 | 39 | | onSuccess = successCallback; |
| 417 | 40 | | } |
| 313 | 41 | | else if (!failed) |
| | 42 | | { |
| 312 | 43 | | successCallback?.Invoke(value); |
| | 44 | | } |
| | 45 | |
|
| 730 | 46 | | return this; |
| | 47 | | } |
| | 48 | |
|
| | 49 | | public void Catch(Action<string> errorCallback) |
| | 50 | | { |
| 60 | 51 | | if (!resolved) |
| | 52 | | { |
| 28 | 53 | | onError = errorCallback; |
| 28 | 54 | | } |
| 32 | 55 | | else if (failed) |
| | 56 | | { |
| 1 | 57 | | errorCallback?.Invoke(this.error); |
| | 58 | | } |
| 32 | 59 | | } |
| | 60 | |
|
| | 61 | | public void Dispose() |
| | 62 | | { |
| 16 | 63 | | onSuccess = null; |
| 16 | 64 | | onError = null; |
| 16 | 65 | | resolved = true; |
| 16 | 66 | | } |
| | 67 | | } |
| | 68 | | } |