Is there a better way to do callback chaining in javascript?

后端 未结 2 865
北海茫月
北海茫月 2021-01-20 16:13

I wrote a callback helper, that lets me group multiple callbacks into one function variable:

function chainCallbacks() {
    var callbacks = arguments;
    r         


        
相关标签:
2条回答
  • 2021-01-20 16:51

    If you want to replace a callback with one that calls the original as well as some others, I'd probably just do something like this:

    Requirejs.config.callback = function(orig) {
        var fns = [orig, first, second, third];
        return function() {
            fns.forEach(function(fn) { fn.apply(null, this); }, arguments);
        };
    }(Requirejs.config.callback);
    

    But if you're doing this often, I think your solution will be as good as it gets. I don't see need for a library.

    Requirejs.config.callback = chainCallbacks(Requirejs.config.callback, first, second, third)
    

    A library can't do anything to extend language syntax in JavaScript. It's limited to what's available... no operator overloading or anything.

    0 讨论(0)
  • 2021-01-20 17:04

    I have modified your chainCallbacks function. You can test below code in JS console (I'm using Chrome -works fine), and check the result.

    var result = 0;
    
    function a() {
            result += 5;
            console.log(result);
            _next();
    }
    
    function b() {
            result += 10;
            console.log(result);
            _next();
    }
    
    function c() {
            result += 20;
            console.log(result);
            _next();
    }
    
    function chainCallbacks() {
    
        var _this = this;
        var _counter = 0;
        var _callbacks = arguments;
    
        var _next = function() {
            _counter++;
            if(_counter < _callbacks.length) {
                _callbacks[_counter].apply(_this);
            }
        };
    
        _this._next = _next;
    
        return function() {
            if(_callbacks.length > 0) {
                _callbacks[0].apply(_this);
            }
        };
    }
    
    var queue = chainCallbacks(a, b, c);
    queue();
    

    Idea is simple - you call _next() whenever your callback function has finished executing, and you want to jump to another. So you can call _next() e.g. after some jQuery animation as well, and this way you will preserve the order of the functions.

    0 讨论(0)
提交回复
热议问题