JavaScript Callbacks and Splunk

JavaScript Callbacks and Splunk

本文关键字:Splunk and Callbacks JavaScript      更新时间:2023-09-26

我正在使用Splunk Javascript API来访问它的一些功能,但我很难理解回调背后的Javascript概念。

文档中的一个示例:

var http = new splunkjs.ProxyHttp("/proxy");
var service = new splunkjs.Service(http, {
    username: username,
    password: password,
    scheme: scheme,
    host: host,
    port: port,
    version: version
});
Async.chain([
        // First, we log in
        function(done) {
            service.login(done);
        },
        // Perform the search
        function(success, done) {
            if (!success) {
                done("Error logging in");
            }
            service.search("search index=_internal | head 3", {}, done);
        },
        // Wait until the job is done
        function(job, done) {
            Async.whilst(
                // Loop until it is done
                function() { return !job.properties().isDone; },
                // Refresh the job on every iteration, but sleep for 1 second
                function(iterationDone) {
                    Async.sleep(1000, function() {
                        // Refresh the job and note how many events we've looked at so far
                        job.fetch(function(err) {
                            console.log("-- fetching, " + (job.properties().eventCount || 0) + " events so far");
                            iterationDone();
                        });
                    });
                },
                // When we're done, just pass the job forward
                function(err) {
                    console.log("-- job done --");
                    done(err, job);
                }
            );
        },
        // Print out the statistics and get the results
        function(job, done) {
            // Print out the statics
            console.log("Job Statistics: ");
            console.log("  Event Count: " + job.properties().eventCount);
            console.log("  Disk Usage: " + job.properties().diskUsage + " bytes");
            console.log("  Priority: " + job.properties().priority);
            // Ask the server for the results
            job.results({}, done);
        },
        // Print the raw results out
        function(results, job, done) {
            // Find the index of the fields we want
            var rawIndex        = utils.indexOf(results.fields, "_raw");
            var sourcetypeIndex = utils.indexOf(results.fields, "sourcetype");
            var userIndex       = utils.indexOf(results.fields, "user");
            // Print out each result and the key-value pairs we want
            console.log("Results: ");
            for(var i = 0; i < results.rows.length; i++) {
                console.log("  Result " + i + ": ");
                console.log("    sourcetype: " + results.rows[i][sourcetypeIndex]);
                console.log("    user: " + results.rows[i][userIndex]);
                console.log("    _raw: " + results.rows[i][rawIndex]);
            }
            // Once we're done, cancel the job.
            job.cancel(done);
        }
    ],
    function(err) {
        callback(err);        
    }
);

Async.chain在这里被定义为root.chain = function(tasks, callback)。我的理解是,任务数组中有5个函数,它们一个接一个地执行,并将结果从一个传递到另一个。

然而,我不明白"完成"、"成功"、"工作"answers"结果"是如何定义的,在哪里定义的,或者它们是如何在其职能范围内用作论据的?

  function(success, done) {
            if (!success) {
                done("Error logging in");
            }
            service.search("search index=_internal | head 3", {}, done);
  }

在这里,它是如何测试成功的,并向done()传递字符串的?

以及这两个功能是如何实现的

function(job, done) {// Print out the statics ..}
&
function(results, job, done) { .. }

将结果数据从第一个函数传递到第二个函数?

为这个长问题道歉。

在Javascript中,函数创建新的作用域。这意味着在传递给函数之前,传递的参数的名称并不重要。

var awesomeName = 'bob';
hi(awesomeName);
// name === undefined
function hi(name) {
    // name === 'bob';
    console.log('hi', name); // Outputs: 'hi bob' in console
}
// name === undefined

正如您所说,每个任务都会调用下一个任务作为回调。最后一个参数始终是下一个任务函数/回调。这意味着Async.chain可能会在调用每个任务函数之前自动将回调添加到参数的末尾。done只是分配给回调的一个常规名称。类似地,其他参数只是上一个任务传递的参数的描述性名称。为了了解它们以这种方式命名的原因,您应该查看调用回调的函数。

例如:

service.login(done)中可能有某种代码可以执行类似的操作:

login: function(callback) {
    var successful;
    // Do Login logic here and assign true/false to successful
    callback(successful);
}

回调是链中的下一个任务,有两个参数successdonesuccess只是login传递给它的第一个参数。Async.chain总是传递另一个参数作为最后一个参数:下一个任务函数,它只是按惯例分配了名称done。您可以在每个函数中随意命名它,只要您在函数中使用相同的名称即可。

function cb(success, fuzzyCallback) {
  if (!success) {
    fuzzyCallback('Error!');
  }
  fuzzyCallback(null);
}