Skip to content

Instantly share code, notes, and snippets.

@nimamehanian
Created August 16, 2015 02:15
Show Gist options
  • Save nimamehanian/e5c8224f1c58d61c37ad to your computer and use it in GitHub Desktop.
Save nimamehanian/e5c8224f1c58d61c37ad to your computer and use it in GitHub Desktop.
Obligation
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