To write a Promise class in Swift, you can start by creating a generic class that represents a value that may not yet be available. Here is an example implementation:
main.swift691 chars28 linesThis Promise class has a private result property that is set when the promise is resolved, and a list of callbacks that are called when the promise is resolved. The resolve() method updates the result property and calls all registered callbacks.
The then() method is a way to chain promises. It takes a closure that accepts the T value of this promise and returns another promise (Promise<U>). When this promise is resolved, the closure is executed, and the resulting promise is resolved with the same result. If the current promise fails, the resulting promise is also failed.
Example usage:
main.swift414 chars18 linesIn this example, fetchTodo() returns a promise that is resolved after one second. We chain two calls to then() that log the todo and call fetchTodo() again. The resulting promise (todoList) is the last promise in this chain.
gistlibby LogSnag