Sunday, 15 July 2012

javascript - Add a then method to a function for callbacks -



javascript - Add a then method to a function for callbacks -

i've seen few bits of code so:

myfunc(args).then(function() { ... });

i find callback syntax elegant. understanding not part of vanilla js, , i'd able utilize on occasion without depending on particular libraries, i'm interested in how implement myself. so, how kind of thing work, , how implement function call?

this pattern called "promises". implemented jquery , dojo among others, , 1 approach @ code , see how implement it.

the general implementation pattern creating function returns object includes function (then) pass pair of function in callbacks previous method run either on success or failure. msdn has more promises in blog post here

there's minimalist implementation posted on github here: promises gist

function promise () { this._thens = []; } promise.prototype = { /* "front end" api. */ // then(onresolve, onreject): code waiting promise uses // then() method notified when promise complete. there // 2 completion callbacks: onreject , onresolve. more // robust promise implementation have onprogress handler. then: function (onresolve, onreject) { // capture calls then() this._thens.push({ resolve: onresolve, reject: onreject }); }, // promise implementations have cancel() front end end api // calls of onreject() callbacks (aka "cancelable promise"). // cancel: function (reason) {}, /* "back end" api. */ // resolve(resolvedvalue): resolve() method called when promise // resolved (duh). resolved value (if any) passed resolver // method. waiting onresolve callbacks called // , future ones are, too, each beingness passed resolved value. resolve: function (val) { this._complete('resolve', val); }, // reject(exception): reject() method called when promise cannot // resolved. typically, you'd pass exception single parameter, // other argument, including none @ all, acceptable. // waiting , future onreject callbacks called when reject() // called , passed exception parameter. reject: function (ex) { this._complete('reject', ex); }, // promises may have progress handler. end api signal // progress "event" has single parameter. contents of parameter // , specific implementation. // progress: function (data) {}, /* "private" methods. */ _complete: function (which, arg) { // switch on sync then() this.then = === 'resolve' ? function (resolve, reject) { resolve(arg); } : function (resolve, reject) { reject(arg); }; // disallow multiple calls resolve or reject this.resolve = this.reject = function () { throw new error('promise completed.'); }; // finish waiting (async) then()s var athen, = 0; while (athen = this._thens[i++]) { athen[which] && athen[which](arg); } delete this._thens; } };

(note not code. looked through , looks starting point, credit goes original author)

javascript callback

No comments:

Post a Comment