Last active
December 24, 2015 08:29
-
-
Save dmi3y/6771024 to your computer and use it in GitHub Desktop.
http://www.youtube.com/watch?feature=player_detailpage&v=ya4UHuXNygM#t=2598 http://jsbin.com/ajoFEF/2/edit
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
function make_promise() { | |
var status = 'unresolved', | |
outcome, | |
waiting = [], | |
dreading = []; | |
function vouch (deed, func) { | |
switch (status) { | |
case 'unresolved': | |
(deed === 'fulfilled' ? waiting: dreading).push(func); | |
break; | |
case deed: | |
func(outcome); | |
break; | |
} | |
} | |
function resolve(deed, value) { | |
if (status !== 'unresolved') { | |
throw new Error('The promise has already been resolved: ' + status); | |
} | |
status = deed; | |
outcome = value; | |
(deed === 'fulfilled' ? waiting: dreading).forEach(function (func) { | |
try { | |
func (outcome); | |
} catch (ignore) {} | |
}); | |
waiting = null; | |
dreading = null; | |
} | |
return { | |
when: function (func) { | |
vouch('fulfilled', func); | |
}, | |
fail: function (func) { | |
vouch('smashed', func); | |
}, | |
fulfill: function (value) { | |
resolve('fulfilled', value); | |
}, | |
smash: function (string) { | |
resolve('smashed', string); | |
}, | |
status: function () { | |
return status; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment