开发者

in javascript, using callback functions recursively for loop control - is this dangerous?

in the following code cannot use a for loop over the array since each step is nonblocking and requires a callback function

Theory of Operation: A form submit calls verify() where el is the HTMLFormElement and nextFunc is the callback function. each element contained in the开发者_如何学编程 form is verified with verifyCol(), breaking out to nextFunc(err) on the first error returned, or, when done, to nextFunc().

// verify as called from post
Post.prototype.verify = function( el, nextFunc ) {
        var post = this;     
        var arr = this.entryArr(el);
        (function verifyOne( i ) {
                if( i >= arr.length ) nextFunc();
                else post.colVerify( arr[i], function(err) {
                        if( err ) nextFunc( err );
                        else verifyOne( i+1 );
                } );    
        })(0);          
}

This approach makes sense to me (although suspiciously looks like Lisp).

Is this the correct paradigm here? Are there any dangers in calling callback functions recursively?


JavaScript is a lisp variant (descendant from scheme), that is why it looks like lisp.

There is no recursion in the code above (in the strictest definition of recursion) if the post function is a callback function from a HTTP request -- the functions are simply handles which are kept as references and invoked though the event queue when the HTTP post returns with data.

Whether recursion can be used in JavaScript for loop recursion is depending on whther the JavaScript Interpreter have implemented tail-call-optimization but most JavaScript implementations (add a comment if you know of any) does not have that implemented, so generally loop recursion (that is calling the function without putting the call on the event queue) may cause problems if the call stack becomes too deep.

In your case, the verifyOne call is never called until the post comes back from the previous call, and hence your loop is through the event queue

The program paradigm look ok and textbook-like to me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜