Mark McDonnell wrote: > On Tuesday, 29 March 2011 at 19:57, Scott Sauyet wrote: >> Mark McDonnell wrote: >> > Hi Scott, yes that is the type of thing I'm trying to achieve >> (and was failing horribly to explain). >> So, now that you have a target API, do you have any approaches to >> solving this? > absolutely none :)
That's why I tried to simplify a starting API: to make it easier to figure out how to implement it. I guess that wasn't enough, huh? > to be honest from all the different implementations I think I > just need to see a working version so I can understand how it > gets put together. > [ ... ] > I've still not quite got my ahead around how they work or to > develop one myself [ ... ] > If anyone knows of anything else like this that is functional > but more full featured so I can learn how it is put together > that would be great. Below is a sample implementation of the API mentioned above. It's not how I would build production code. It's essentially the most naive implementation I can come up with of the API already discussed. There are numerous flaws, including the lack of error-checking, the perhaps- too-simplistic constructors, and even the exposure of the Promise constructor, which although it was listed in the API above seems to have fallen out as mostly an implementation detail that didn't need to be public. There are likely other issues too. You can see a really dumb page that uses this at http://scott.sauyet.com/Javascript/Test/2011-03-29a/ Feel free to ask questions about the implementation, but it's not meant to be model code, only a starting place. Cheers, -- Scott Sample Code =========== var Lib = Lib || {}; Lib.when = function(dfd) { return dfd.promise(); } Lib.Promise = function(then, fail) { this.then = then; this.fail = fail; } Lib.Deferred = function() { var dfd = this, completed = false, val, error, i, len, successFns = [], failureFns = [], then = function(success) { if (completed) { if (typeof val !== "undefined") { success(val); } } else { successFns.push(success); } return myPromise; }, fail = function(failure) { if (completed) { if (typeof error !== "undefined") { failure(val); } } else { failureFns.push(failure); } return myPromise; }, myPromise = new Lib.Promise(then, fail); this.promise = function() {return myPromise;}; this.resolve = function(returnVal) { if (!completed) { completed = true; val = returnVal; for (i = 0, len = successFns.length; i < len; i++) { successFns[i](val); } } }; this.reject = function(returnError) { if (!completed) { completed = true; error = returnError; for (i = 0, len = failureFns.length; i < len; i++) { failureFns[i](error); } } }; }; -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/ To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/ To unsubscribe from this group, send email to [email protected]
