| | 1 | | using System; |
| | 2 | | using UnityEngine; |
| | 3 | |
|
| | 4 | | namespace DCL.Helpers |
| | 5 | | { |
| | 6 | | public class Promise<T> : CustomYieldInstruction, IDisposable |
| | 7 | | { |
| 1252561 | 8 | | internal bool resolved { get; private set; } |
| 855 | 9 | | internal bool failed { get; private set; } |
| 584 | 10 | | internal PromiseException exception { get; private set; } |
| | 11 | |
|
| | 12 | | internal Action<T> onSuccess; |
| | 13 | | internal Action<string> onError; |
| | 14 | |
|
| 1251513 | 15 | | public override bool keepWaiting => !resolved; |
| 924 | 16 | | public T value { private set; get; } |
| 6 | 17 | | public string error => exception?.Message; |
| | 18 | |
|
| | 19 | | public void Resolve(T result) |
| | 20 | | { |
| 577 | 21 | | failed = false; |
| 577 | 22 | | resolved = true; |
| 577 | 23 | | value = result; |
| 577 | 24 | | exception = null; |
| 577 | 25 | | onSuccess?.Invoke(result); |
| 154 | 26 | | } |
| | 27 | |
|
| | 28 | | public void Reject(string errorMessage) |
| | 29 | | { |
| 1 | 30 | | failed = true; |
| 1 | 31 | | resolved = true; |
| 1 | 32 | | exception = new PromiseException(errorMessage); |
| 1 | 33 | | onError?.Invoke(error); |
| 0 | 34 | | } |
| | 35 | |
|
| | 36 | | public Promise<T> Then(Action<T> successCallback) |
| | 37 | | { |
| 543 | 38 | | if (!resolved) { onSuccess = successCallback; } |
| 469 | 39 | | else if (!failed) { successCallback?.Invoke(value); } |
| | 40 | |
|
| 389 | 41 | | return this; |
| | 42 | | } |
| | 43 | |
|
| | 44 | | public void Catch(Action<string> errorCallback) |
| | 45 | | { |
| 3 | 46 | | if (!resolved) { onError = errorCallback; } |
| 2 | 47 | | else if (failed) { errorCallback?.Invoke(this.error); } |
| 1 | 48 | | } |
| | 49 | |
|
| | 50 | | public void Dispose() |
| | 51 | | { |
| 38 | 52 | | onSuccess = null; |
| 38 | 53 | | onError = null; |
| 38 | 54 | | resolved = true; |
| 38 | 55 | | } |
| | 56 | | } |
| | 57 | | } |