Inspired by Signal’ promise source code, I now build a simple version of “Promise” with main point : Provide a clean interface for running a task on a specific queue, and work with multiple completion handlers.
Running block on a specific queue, it’s just this simple :
Here, we handle the chain of completion even :
Just how does “then” work ???
It waits for the “Promise” to be resolved and then resolves all blocks inside observes.
Next point : what if we have some tasks like NSURLSession inside Promise.firstly and we want to activate “then” only when the task completes ?
I come up with Promise.firstlyWithCompletion
And here, we can activate multiple “then” after the completion of firstly block:
Easy enough ? Just the very simple version. Of course the real code of Signal is much more complicated. However, as my main purpose is to dig deep into the main idea of Promise and do practice, it is quite a sufficient version. Of course this article is not to provide any lib, module because google’s FBP promise is already there , however, anyone can take inspiration, research deep and understand what stands behind the in-use API.
Further research, for simplicity, I don’t use a future inside Promise. However, it is good to move the initWithTask, resolve, sealResult into the main logic of Future.
Source code : https://github.com/mihozil/ZLPromise