Send arguments to a callback function within an Elasticsearch JavaScript API search query

I have a function that requires an aggregation for each word entered by the user and then generates a chart.

I am wondering how I can access the value of the variable i from my loop in the callback when the request is made.

Is there a way to include the variable i in the predefined parameters set by the elasticsearch API?

for(var i = 0; i < 15; i++)
{
    client.search({
        index: 'twitter',
        type: "status",
        size : 10,
        body: 
        {
            query: {
                "bool": {
                    "must": [
                        {"query_string": {
                            "fields" : ["text"],
                            "default_operator" : "AND",
                            "query" : $scope.motsCompares[i]
                        }},
                        {"range": {
                            "created_at": {
                                "gte": moment().subtract(duration, key).format("YYYY-MM-DD")
                            }
                        }}
                    ]
                }
            },
            aggs : {
                "frequence_mots" : {
                    "date_histogram" : {
                        "field" : "created_at",
                        "interval" : "day",
                        "format" : "dd/MM/yyyy",
                        "min_doc_count" : 0
                    }
                }
            }
        }
    }).then(function traiterResultat(body) {

        // Here's where I want to refer to the current i value from the loop to access the right word in my array ($scope.motsCompares[i])

    }, function (error) {
            console.trace(error.message);
    });
}

Answer №1

Back in the day, without the convenience of fn.bind(), developers had to resort to closures or other less-than-ideal methods that shall remain unnamed.

But fear not! Thanks to ECMAScript 5, we now have the power of "currying" with fn.bind(). This allows us to pass i upfront and body later on when our promise chain is ready to unleash its success sequence.

for(var i = 0; i < 15; i++) {
    (function(i) {
        client.search({
            // ...
        }).then(function (i, body) {
            // The callback function inside .then() is actually an intermediary function created by .bind().
            // Here, `i` corresponds to the loop's `i` value bound-in using .bind().
            // The actual value for `body` will be supplied to this intermediary function once the promise completes successfully.
        }.bind(null, i), function (error) {
            console.trace(error.message);
        });
    })(i);
}

And don't forget, you can always replace null within .bind(null, i) with any object that you want to serve as the context for the callback function.

Answer №2

Implement a different approach for your callback:

for(var j = 0; j < 15; j++)
{
  client.search({
                  index: 'twitter',
                  type: "status",
                  size : 10,
                  body:
                  {
                    query: {
                      "bool": {
                        "must": [
                          {"query_string": {
                            "fields" : ["text"],
                            "default_operator" : "AND",
                            "query" : $scope.motsCompares[j]
                          }},
                          {"range": {
                            "created_at": {
                              "gte": moment().subtract(duration, key).format("YYYY-MM-DD")
                            }
                          }}
                        ]
                      }
                    },
                    aggs : {
                      "frequence_mots" : {
                        "date_histogram" : {
                          "field" : "created_at",
                          "interval" : "day",
                          "format" : "dd/MM/yyyy",
                          "min_doc_count" : 0
                        }
                      }
                    }
                  }
                }).then(createCustomCallback(j), function (error) {
                          console.trace(error.message);
                        });
}

function createCustomCallback(j){
  return function processResult(body) {

    // utilize j from the loop here to access the correct word in my array ($scope.motsCompares[j])

  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a new Chart.js Chart by using the data retrieved from an AJAX request and encoded in JSON

I am currently working on drawing a chart using the chart.js library. The initial draw works perfectly fine, but I am facing issues when trying to redraw the doughnut chart with new data retrieved from an ajax call. My approach involves PHP and Codeignite ...

Patience is key when using JavaScript

I have a JavaScript function that is responsible for updating my data. When the user clicks multiple times, I need to wait for the second click until the first one has finished processing, and so on. $scope.isLastUpdateFinished = true; $ ...

Numerous levels of nested closures working alongside synchronous JavaScript code

After receiving an explanatory answer to my previous inquiry, I realize that my initial question lacked sufficient context to address my current situation effectively. Let me present a specific route within my Express application: var eventbriteService = ...

What measures can be taken to safeguard this hyperlink?

Is there a way to conceal HTML code from the source code? For instance: jwplayer("mediaplayer").setup({ file: "http://example.com/Media.m3u8", autostart: 'true', controlbar: 'bottom', file: "http://exa ...

What is the best way to remove an item from an array inside another object in JavaScript?

I am currently developing an application using Node, mongoose, and express. My goal is to remove an object from an array that is nested inside another object. Here is the structure of the objects: const oldSection = { _id: '62d3f1d221aa21a03fe3bc21& ...

The 'fetch' operation could not be completed on the current window due to a TypeError

The error message I am receiving is: TypeError: Failed to execute 'fetch' on 'Window' : The provided value is not of type '(sequence<sequence> or record<ByteString, ByteString>)'. My current challenge involves fetc ...

The Express middleware type cannot be assigned as expected

I'm encountering an error where my first middleware is being red underlined. I can't figure out why it's only happening to the first one. https://i.sstatic.net/PahAz.png https://i.sstatic.net/GgxBy.png Can anyone provide some guidance on ...

Adjusting the styling of slick.js carousel when the slide changes

Is it feasible to change the CSS for a div on a slick.js slider change? Essentially, I want to cycle through an array of colors and set the background color of .content to that color when the slider autoplays or when a button is clicked. Am I being too amb ...

What is the best way to retrieve a value from within several functions?

Below is the code I have been working on: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function() { this.addEventListener('load', function() console.log(this.responseTex ...

The display in xtermjs appears distorted, showing skewed text instead of displaying correctly

After saving data from a tmux session using capture-pane into a file.txt, the output can look like this: PC1:/path$ cd /usr PC1:/usr$ ll total 0 drwxr-xr-x 1 root root 4096 May 21 2019 [1;34m.[0;39m/ drwxr-xr-x 1 root root 4096 Aug 1 2019 [1;34m..[0;39m/ d ...

Ajax disregards the endless scroll material that has been injected into the DOM

I am currently facing an issue with loading posts on a page using foreach and the paginate function in Laravel. I have set up infinite scrolling through the posts, with each post having its own unique form. The first posts that load without JavaScript scro ...

Troubleshooting: Unable to Trigger jQuery AJAX Function

I've searched high and low, both here and elsewhere, in an attempt to solve this issue. Unfortunately, I haven't been able to come across anything quite like it. The button click works fine as it prints to the console. However, any subsequent con ...

Mongoose stores data in two separate collections

Hey everyone, I could really use some assistance with this issue that has been bothering me for the past few days. model/user.js var UserSchema = mongoose.Schema({ username:{ type: String, unique: true, index:true }, password:{ type:Strin ...

Is it possible to generate a unique name from an array without any repeats?

Update: I am not looking to create a single list, but rather a button that generates a random name when clicked. Objective: Generate a random name from an array by clicking a button. The goal is to display one name at a time randomly without repetition. W ...

Trouble with parseJSON when handling form POST in Python

I'm struggling with a javascript HTML page that has an action POST to a python file, expecting a JSON response back. Despite my efforts, I can't figure out how to catch and parse the JSON data. The HTML and python code excerpts below should show ...

Continuously inserting new records to a JSON file using a while loop

Is there a way to continuously add key value pairs to a JSON object within a while loop? var sName = "string_"; var aKeys = ["1", "2", "3"]; var sKey = "key"; var n = 1; var aObj = {}; var l = aKeys.length; for(let i=0; i < l; i++){ while(n < 5) ...

Empty Canvas: Google Charts Graph Fails to Populate

I am currently using mysql, php, and javascript to display a curve chart. The issue I am facing is that the chart appears blank. google.load('visualization', '1.0', {'packages':['corechart']}); google.setOnLo ...

What is the best way to verify the status codes of multiple URLs using JavaScript?

In my JavaScript project, I am currently checking the status codes of various URLs. While I can successfully check the status for one URL at a time by writing the code manually, I am facing an issue as I have over 100 URLs to check. This is making my cod ...

Only displaying the VUE slot when the content meets a certain criteria

I have encountered a situation where I have two routes rendering the same component but with different data from an API source. The component in question has a child component called <base-section> that utilizes a v-if directive to determine whether ...

The V-model binding feature seems to be malfunctioning on mobile devices, unless I incorporate an alert into the

Encountering a strange issue with form input binding in my Vue application. The input field is an auto-suggest search field with the following set up: <input class="input" type="text" v-model="search" @input="onChange" @keyup.up="onArrowUp" @keyup.down ...