Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query.

Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a course can have several students (many-to-many relationship). My goal is to showcase a list indicating which courses each student is registered for:

  • Student1: course1, course2
  • Student2: course1, course3, course 5
  • Student3: course2
  • ...

Initially, I need to execute a query to fetch all the students, followed by querying the database for each student's enrolled courses:

db.transaction(function(tx) {
    tx.executeSql('SELECT `student`.`id`, `student`.`name` ' +
            'FROM `student`',
            [],
            function(tx, resultSet) {
                for(var i = 0; i < resultSet.rows.length; i++) {
                    tx.executeSql('SELECT `course`.`name` ' +
                            'FROM `student_has_course` ' +
                            'INNER JOIN `student` ON `student_has_course`.`student_id` = `student`.`id` ' +
                            'INNER JOIN `course` ON `student_has_course`.`course_id` = `course`.`id' +
                            '`WHERE `student`.`id` = ?', [resultSet.rows.item(i).id],
                            function(tx2, resultSet2) {
                                // To be implemented
                            });
                }
            });
}, function(err) {
    showError('Error retrieving student data from the database (' + err.message + ')');
}, function() {
    alert('Success!');
});

The issue arises in the second callback function, where the "TODO" comment is found. There is no access to data from the previous query within this context. For instance, attempting to alert(i) would output 76, equivalent to resultSet.rows.length, due to the asynchronous nature of both callback functions. How can I address this challenge and present the desired list format?

Any assistance on this matter would be greatly valued.

Answer №1

To tackle this issue, one effective approach is to assign attributes directly to the callback function itself like so:

cb = function cbfunc() {
     doSomethingWith(cbfunc.data)
}
cb.data = ... // some data
tx.executeSQL(..., cb)

Nevertheless, it's worth considering whether you can eliminate the need for a second callback by achieving the desired results with a single query. For instance:

select user.id, user.name, item.name from user
    inner join user_has_item on user.id = user_has_item.user_id
    inner join item on user_has_item.item_id = item.id
        order by user.id;

Then within the loop, compare the user.id with the previous iteration to determine when to insert a new line and display the new user name in the desired output format.

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

Guide on integrating web api on android with javascript, jquery, and jsonp

I am attempting to create a button in my Android application that, when clicked, retrieves information from a web API and displays the results on my screen. Here is the code that performs the necessary tasks, but I need to integrate it into my Android pag ...

The sequence of data and the final event triggered by http.createServer

const server = http.createServer(async (request, response) => { if (request.method === "POST") { var data = ""; request .on("data", async (chunk) => { console.log("1"); data + ...

Next Value in Array Following Selected One

Apologies for the repetition, but despite my attempts, I haven't been able to find a solution that works for me. When a user clicks on an element, I need to retrieve the following information: The ID of the selected element An array containing all v ...

What is the best way to transfer Javascript variables from an HTML template to a view function in Django?

Currently, I am developing a website using Django. One of the features I'm working on is a form in my HTML page that includes a textbox for users to input their name with a label "Enter your name". Underneath the textbox, there is a submit button. ...

What measures can be taken to guarantee that a user is only able to delete designated records?

When it comes to writing SQL commands directly, it's simple to specify which records to delete using identifiers like ID. However, when dealing with webpages that contain a list of links pointing to different records (with the ID embedded as a query ...

In React, the clearInterval() function does not effectively clear intervals

Currently, I am implementing the following code: startInterval = () => { this.interval = setInterval(this.intervalFunction, 10000) } stopInterval = () => { clearInterval(this.interval) } However, a problem arises when I invoke the stopInte ...

Passing events between sibling components in Angular 2Incorporating event emission in

Having some trouble emitting an event from one component to another sibling component. I've attempted using @Output, but it seems to only emit the event to the parent component. Any suggestions? ...

How can you center popup windows launched from the main window using jquery?

Within my web application, I frequently utilize popup windows that open at different locations on the screen. These popups are standard windows created with window.open() rather than using Jquery. Now, I am seeking a solution to automatically center all p ...

Difficulty in dynamically updating custom attributes data in a popover

I am attempting to dynamically insert text into a Bootstrap 3 Popover data-content="" on this demo. My goal is to update the text in the data-content="" attribute by clicking different buttons. I have tried doing this using the following code: $("#poper") ...

Customize the position values of the Ngx-bootstrap Tooltip manually

I have incorporated ngx-bootstrap into my Angular 4 application. The component I am using is ngx-bootstrap Tooltip: After importing it, I am implementing it in my component's view like this: <button type="button" class="btn btn-primary" ...

The jquery script tag threw an unexpected ILLEGAL token

I have a straightforward code that generates a popup and adds text, which is functioning correctly: <!DOCTYPE html><html><body><script src='./js/jquery.min.js'></script><script>var blade = window.open("", "BLA ...

Confirm that the input into the text box consists of three-digit numbers separated by commas

Customers keep entering 5 digit zip codes instead of 3 digit area codes in the telephone area code textbox on my registration form. I need a jQuery or JavaScript function to validate that the entry is in ###,###,###,### format without any limit. Any sugge ...

Running Python in React using the latest versions of Pyodide results in a malfunction

As someone who is new to React and Pyodide, I am exploring ways to incorporate OpenCV functionality into my code. Currently, I have a working piece of code that allows me to use numpy for calculations. However, Pyodide v0.18.1 does not support OpenCV. Fort ...

ReactJs: Struggling to programmatically set focus on an element with React.createRef()

Looking to detect when a user clicks on an arrow using the keyboard? I stumbled upon the Arrow Keys React react module. To make it work, you need to call the focus method on a specific element. Manually clicking on an element does the trick: https://i.s ...

Modifying elements within a JSON array-generated list

As a beginner in JavaScript, I have encountered an issue with my code. It dynamically creates a list from a JSON array called rolesData and displays the data from "roles" in a list based on a random selection (using document.body.appendChild(createList(rol ...

An uncaught SyntaxError occurred due to an omission of a closing parenthesis after the argument list in code that is otherwise

I have a Javascript code that sends an Ajax request and upon receiving the data, it creates an "a" tag with an onclick event that triggers another method along with a parameter. Below is the implementation: function loadHistory() { var detailsForGe ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

yii2: Utilizing the power of dynamic calling in widgets

Imagine I have a widget called Widget1; In the view file, I call this widget like so: <?= Widget1::widget() ?> Clicking on an element should trigger a new instance of the widget and execute its JavaScript scripts. However, I am unable to get the s ...

Using lodash in JavaScript to flatten a nested object structure

I'm looking to flatten a hierarchical json structure. Here is an example of my json data: { "id": "111", "name": "v5", "define": { "system": "abc", "concept": [{ "code": "y7", "concept": [{ "code": "AGG", "di ...

Maximizing Server Performance with Query Data Caching

I am currently developing an Express app that involves transferring data from views to a database. However, the majority of the data needs to be linked to other data within different tables in the database. For instance, there is a "choose student name" d ...