connecting parameters to functions in javascript

I'm attempting to execute a second query once the first query has been resolved by using the following code:

const task1 = nextQuery => $.get('1.json', data => nextQuery());
const task2 = nextQuery => $.get('2.json', data => nextQuery());
const task3 = nextQuery => $.get('3.json', data => nextQuery());
const task4 = nextQuery => $.get('4.json', data => nextQuery());

const tasks = [task1, task2, task3, task4];

const tasksWithArgs = tasks.map((taskFn, index, arr) => {
    const followingTask = arr[index + 1];
    
    if (!followingTask) {
        return;
    }
    
    return taskFn.bind(taskFn, followingTask);
});

tasksWithArgs[0]();

Despite successful requests to 1.json and 2.json, I am encountering a TypeError: nextQuery is not a function. It seems that fn2 is not receiving fn3 as an argument. Can you provide an explanation of how this code operates?

Answer №1

It appears that there may be some confusion regarding the arr argument and its connection to the queriesWithArgs array. The arr actually references the original queries array, leading to issues when trying to call the nextQuery functions without providing an additional argument.

A more suitable solution in this scenario would involve utilizing reduceRight instead of map. This way, the nextQuery accumulator will correctly point to the previous result or initial value (in this case, the last callback):

const queries = [fn1, fn2, fn3, fn4];

const run = queries.reduceRight((nextQuery, queryFn) => {
    return queryFn.bind(null, nextQuery);
}, function last() {
    console.log("done");
});

run();

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

Is it possible to create a button on-click feature without the traditional button appearance?

Currently, I am creating a button using React, but I don't want it to have the traditional button appearance. Is there a way for me to make it a clickable div without the default button style? Below is the code I am working with: <div style={style ...

How to access iFrame in ReactJS using document.getElementById

I am facing a challenge on my website where I need to transfer data (using postMessage) to an iframe. Typically in plain JavaScript, I would use techniques like document.getElementById or $("#iframe") in jQuery to target the iframe. However, I am unsure ...

Issue with data interpretation between jQuery and Java

My character encoding is currently set to ISO-8859-1. I'm utilizing an AJAX call with jQuery.ajax to communicate with a servlet. After serialization by jQuery, the URL appears as follows: https://myurl.com/countryAndProvinceCodeServlet?action=getPro ...

`Inquiry into AJAX form submission problem`

Here is the HTML markup and JS code for my signup page. I encountered an issue where, if I leave all text inputs blank and click submit for the first time, it validates and shows an error message. However, when I click submit a second time, it directly sen ...

How to create a fresh factory instance in Angular Js

I have implemented a factory in my application to retrieve a list of folders and display it on the front end. Additionally, I have a form on the front end where users can add new folders to the existing list. After adding a folder, I need to refresh my fac ...

After successfully deploying to the server, the Intel XDK Ajax Access feature is restricted [functioning properly on xampp]

I developed an XDK app that was functioning perfectly on xampp. I managed to fix the header issue, but when I uploaded it to a live server, the ajax call stopped working and I encountered this error: XMLHttpRequest cannot load http://watanydemo.eb2a.com/m ...

The function chartobject-1.render() is returning an error message stating: "Unable to locate the specified container within the document. This issue is occurring in the

I've encountered an issue while trying to integrate FusionCharts into my Vue.js project. Every time I attempt to render the charts within my components, I consistently run into this error. Here's a snippet of one of the components: <template&g ...

PHP - Is it possible to transfer the name of a POST method from one page to another in PHP?

How can I retrieve and check the value of a select option from one page to another using PHP? Specifically, I want to access the POST name ($_POST['selection_value']) and validate if it matches a certain selection value (e.g., 'time'). ...

Having trouble getting routing to function properly with react-router-dom

I'm currently assisting a friend with completing a React Project. I'm facing an issue while trying to set up routing using react-router-dom. The components inside the <switch> tag are not functioning properly. Below are snippets of my code: ...

Collaborate on React-Native components together!

As a newcomer to the world of react, react-native, and nodejs, I embarked on creating my own node module using npm init. Within this module, I developed a component for styling buttons, packaging it with npm pack and linking it in my application's pac ...

How to retrieve TypeScript object within a Bootstrap modal in Angular

Unable to make my modal access a JavaScript object in the controller to dynamically populate fields. Progress Made: Created a component displaying a list of "person" objects. Implemented a functionality to open a modal upon clicking a row in the list. ...

Why does my ajax request show the result in the php file rather than redirecting to the html page?

I've developed a series of AJAX functions that retrieve data from a PHP file. However, one of the functions redirects to the PHP file to fetch data but fails to return to the HTML page for data insertion. Here is the code used to fetch a table from a ...

Background of jQuery-UI Slider

Can the background color of a jQuery-UI Slider widget be set using JavaScript? This is the default setting: What I am trying to accomplish is the following: The green range should be determined based on historical data. I want to visually show the user ...

Utilizing JSON data as a variable for handling in a Handlebars view within a Node.js/Express application

I am currently seeking a solution to display a view that includes a variable with data fetched from an API. My technology stack involves express, handlebars, and request. Here is the code for the web server's router: const express = require('ex ...

Vue.js does not seem to be properly assigning attributes that are declared within the data object array

Trying to get a hang of vue.js and looking to create dynamic product cards using it: This is the snippet from my HTML file: <div id="app"> <card v-for="products in product" :productname="product.productname"></card> </div> Here&a ...

Troubleshooting Issue with Public File Serving in ExpressJS Deployment (NodeJS/Express)

The directory structure of my project is organized as follows: my_project server.js app.js | | - public | ----------| images | javascripts | stylesheets | -------------- imgs ---scripts.js ---styles.css | | - routes | | - views | ...

The $timeout function in AngularJS seems to be malfunctioning

I'm attempting to add a delayed effect to my view. After a button is clicked, a message is displayed, but I want it to disappear after 2000ms. I have tried implementing a $timeout function based on recommendations I found, but it doesn't seem to ...

Error message: The AJAX POST request using jQuery did not return the expected data, as the data variable could not be

There is a script in place that retrieves the input text field from a div container named protectivepanel. An ajax post call is made to check this text field in the backend. If the correct password is entered, another div container panel is revealed. < ...

Error: The function getAuth has not been defined - Firebase

I have included the code snippets from index.html and index.js for reference. The analytics functionality seems to be working fine, but I am facing an issue with authentication due to an error during testing. Thank you for your help. index.html <script ...

Navigating the implementation of undefined returned data in useQuery hook within Apollo and ReactJS

I am facing an issue with my code where the cookieData is rendered as undefined on the initial render and query, causing the query to fail authentication. Is there a way to ensure that the query waits for the response from the cookie API before running? co ...