简体   繁体   中英

What meaning is return a(function () )?

I studied simple asynchronized JavaScript code, but stuck with return value(function() ). I don't understand it.

How does operate this return value(function())?

function _async(func) {
    return function () {
        arguments[arguments.length++] = function (result) {
            _callback(result);
        };

        (function wait(args){
            for (var i = 0; i < args.length; i++) {
                if (args[i] && args[i].name == '_async_cb_receiver')
                    return args[i](function (arg) {
                        args[i] = arg; wait(args);
                    })}
            func.apply(null, args);

        })(arguments);

        var _callback;

        function _async_cb_receiver(callback) {
            _callback = callback;
        }

        return _async_cb_receiver;
    };
}

return args[i](function (arg) {
    args[i] = arg; wait(args);
})

I don't understand this part. wait(args) just returns args[i] , but parentheses appear and anonymous function is executed. How does this function handle args[i] and what arguments are in arg ?

args is an array of functions. So args[i] is one of these functions, and args[i](something) calls that function with something as the argument.

In this case, something is another function. This function replaces args[i] with its own argument, then calls wait(args) recursively.

This code is pretty convoluted, so I'm not sure what it's doing as a whole. I suspect it's doing something similar to the way promises work, but was written before they were added to the language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM