Created
October 24, 2013 01:12
-
-
Save toruta39/7129664 to your computer and use it in GitHub Desktop.
Promise pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Promise | |
then: (@onResolved, @onRejected) -> | |
return | |
resolve: (val) -> | |
@onResolved val | |
return | |
reject: (err) -> | |
@onRejected err | |
return | |
ajax = (url) -> | |
xhr = new XMLHttpRequest | |
promise = new Promise | |
xhr.open 'GET', url, true | |
xhr.onload = (e) -> | |
if @status is 200 | |
result = JSON.parse @responseText | |
promise.resolve result | |
return | |
xhr.onerror = (e) -> | |
promise.reject e | |
xhr.send() | |
return promise | |
onResolved = (val) -> | |
console.log val | |
onReject = (err) -> | |
console.log err.message | |
ajax('http://...').then onResolved, onReject |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment