Created
August 16, 2015 02:15
-
-
Save nimamehanian/e5c8224f1c58d61c37ad to your computer and use it in GitHub Desktop.
Obligation
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
var isResolvable = function (val) { | |
return val && typeof val.success === 'function'; | |
}; | |
var reference = function (data) { | |
if (isResolvable(data)) { return data; } | |
return { | |
success: function (callback) { | |
return reference(callback(data)); | |
} | |
}; | |
}; | |
var defer = function () { | |
var pending = [], value; | |
return { | |
resolve: function (_value) { | |
if (pending) { | |
value = reference(_value); | |
for (var i = 0; i < pending.length; i++) { | |
value.success(pending[i]); | |
} | |
pending = void 0; | |
} else { | |
throw new Error('This obligation is already resolved.'); | |
} | |
}, | |
success: function (_callback) { | |
var result = defer(); | |
var callback = function (value) { | |
result.resolve(_callback(value)); | |
}; | |
pending ? pending.push(callback) : value.success(callback); | |
return result; | |
} | |
}; | |
}; | |
var Obligation = function () { | |
return defer(); | |
}; | |
// Usage: | |
var ob = new Obligation(); | |
// EXAMPLE 1: chain success handlers, then resolve. | |
ob.success(function (result) { | |
console.log('In order to understand', result); | |
return result; | |
}).success(function (result) { | |
console.log('...a girl must, first, understand', result); | |
return result; | |
}); | |
ob.resolve('recursion'); | |
// EXAMPLE 2: apply success handlers after resolution. | |
ob.resolve('be seen'); | |
ob.success(function (result) { | |
console.log('After resolution, the data may still', result); | |
return result; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment