Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
lol, promise constructor
//
// Promise.swift
// Promise
//
// Created by Benjamin Gruenbaum on 8/12/14.
// Copyright (c) 2014 Tipranks. All rights reserved.
//
import Foundation
public class Promise<T,E>{
var state:PromiseState<T,E> = PromiseState(state: .Pending, value: nil, error: nil)
var fHandlers:[(T) -> ()] = []
var rHandlers:[(E) -> ()] = []
init(fn:((T) -> (), reject:(E) -> ()) -> ()) {
fn({[unowned self] (t:T) in
for handler in self.fHandlers {
handler(t)
}
} ,
{[unowned self] (e:E) in
for handler in self.rHandlers {
handler(e)
}
})
}
private init(){
}
func then<NT,NE>(onFulfilled:(T) -> Promise<NT,NE>) -> Promise<NT,NE>{
var p = Promise<NT,NE>()
fHandlers.append({ (t:T) in
let res = onFulfilled(t)
res.then({ p.fulfill($0) })
res.catch({ p.reject($0) })
})
return p
}
func then<NT>(onFulfilled:(T) -> NT) -> Promise<NT,E> {
var p = Promise<NT,E>()
fHandlers.append({ (t:T) in
let res = onFulfilled(t)
p.fulfill(res)
})
return p
}
func catch<NT,NE>(onRejected: (E) -> Promise<NT,NE>) -> Promise<NT,NE>{
var p = Promise<NT,NE>()
rHandlers.append({ (t:E) in
let res = onRejected(t)
res.then({ p.fulfill($0) })
res.catch({ p.reject($0) })
})
return p;
}
func catch<NT>(onRejected: (E) -> NT) -> Promise<NT,E> {
var p = Promise<NT,E>()
rHandlers.append({ (t:E) in
let res = onRejected(t)
p.fulfill(res)
})
return p
}
private func fulfill(val:T) {
if state.state != .Pending {
return
}
self.state.state = .Fulfilled
self.state.value = val
}
private func reject(err:E) {
if state.state != .Pending {
return
}
assert(self.state.state != .Rejected)
self.state.state = .Rejected
self.state.error = err
}
}
struct PromiseState<T,E> {
var state:State
var value:T?
var error:E?
}
// hack for - unimplemented IR generation feature non-fixed multi-payload enum layout
enum State {
case Pending
case Fulfilled
case Rejected
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.