Function.prototype.promise





2
Date Submitted Thu. Dec. 20th, 2007 6:48 PM
Revision 1 of 1
Helper Fordiman
Tags JavaScript | promise | Prototype
Comments 0 comments
This is a version of my previous entrant, Promise, that will work with prototype, but does not require it. It's slightly more advanced, using .apply here and there.

It's basically a function to allow any other function to poll. Polling is generally regarded as bad practice in object oriented code, but can make very simple the matter of, for example, running a bit of code only after a single-run event (like onload) occurs (whether that be in the future or past), another unrelated bit of code needs to be hack-tracked, or any other generic condition.

Note that when the function runs, it doesn't necessarily run within the scope that's called it. Its context is set to itself, rather than its normal context, and it's asynchronous, so you'll not get a return value. If you use Prototype, you can bind the function and it'll behave as it should in terms of context, but I'm unaware of a way to cause an asynch function to block execution - and you'd really rather that not happen anyway, trust me.
Function.prototype.promise = function () {
/* Arguments:
        condition to be met before running
        polling interval
        arguments for the function
*/

    var __method=this,
        oArgs=arguments,
        args=[],i,__cond=oArgs[0],__intv=oArgs[1];
    for (i=2; i<oArgs.length; i++) args.push(oArgs[i]);
    if (__cond.apply(__cond,args))
        this.apply(this,args);
    else window.setTimeout(function () {
        __method.promise.apply(__method,oArgs);
    },__intv*1000);
}

/* Very simplistic example of use */
function fnc(a) { //What we're promising to do
        alert(a)
}
//Dummy variable that's just not what we need it to be... yet
var valueToTrack=5;

//Make the promise
fnc.promise(
        function() {
                return valueToTrack==4
        },1,'I\'ve kept my promise'
);
// at some point in the future, the condition changes...
setTimeout("valueToTrack--;", 4000);
 

Bryan Elliott

Comments

There are currently no comments for this snippet.

Voting

Votes Down


Newbie matrix