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

Why do I keep encountering a null window object issue while using my iPhone?

Hey there! I've got a React game and whenever the user loses, a new window pops up. const lossWindow = window.open( "", "", "width=500, height=300, top=200, left = 200" ); lossWindow.document.write( & ...

Unable to bring in @material-ui/core/styles/MuiThemeProvider

I'm currently working on a React project that utilizes Material UI React components. My goal is to import MuiThemeProvider in src/index.js with the following code snippet: import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider"; . H ...

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

Attempting to replicate the functionality of double buffering using JavaScript

In my HTML project, I have a complex element that resembles a calendar, with numerous nested divs. I need to refresh this view in the background whenever there are updates on the server. To achieve this, I set up an EventSource to check for data changes on ...

Utilizing AngularJS to include information into JSON-LD

As a newcomer to AngularJS, I find myself stuck in one of my projects. My goal is to convert the user-entered data in a form into the format: << "schema:data" >> and then push and display it within the @graph of the json-ld. Here are my HTML and Angular co ...

Tips for excluding certain parameters in the jslint unparam block

While developing my angular app, I encountered an issue with jslint flagging an unused parameter. Typically in angular, the "$scope" is required as the first parameter in your controller definition. In my case, I prefer using the "this" keyword instead of ...

The data visualization tool Highchart is struggling to load

As I try to integrate highcharts into my website, I encounter an unexpected error stating TypeError: $(...).highcharts is not a function. Below is the code snippet in question: @scripts = {<script src="@routes.Assets.at("javascripts/tracknplan.js")" ty ...

Send information to a different module

I've created a straightforward form component: <template> <div> <form @submit.prevent="addItem"> <input type="text" v-model="text"> <input type="hidden" v-model="id"> <i ...

Encountering a 'oembed is null' error in the firebug console while using JQUERY OEMBED

There seems to be an issue with oembed causing an error message in firebug's console window. Specifically, the error is displayed as: oembed is null oembedContainer.html(oembed.code); This error occurs when clicking on a link that leads to the jquer ...

Accessing content from a text file and showcasing a designated line

Apologies if my wording was unclear... In this scenario, we will refer to the text file as example.txt. The value in question will be labeled as "Apple" My goal is to retrieve example.txt, search for Apple within it, and display the entire line where thi ...

Having trouble with JSONP cross-domain AJAX requests?

Despite reviewing numerous cross-domain ajax questions, I am still struggling to pinpoint the issue with my JSONP request. My goal is simple - to retrieve the contents of an external page cross domain using JSONP. However, Firefox continues to display the ...

Having difficulty using the forEach() method to loop through the array generated by my API

During my troubleshooting process with console.log/debugger, I discovered that I am encountering an issue when attempting to iterate over the API generated array in the addListItem function's forEach method call. Interestingly, the pokemonNameList ar ...

Step-by-step guide for embedding a Big Commerce website into an iframe

Can a website be opened inside an iframe? If not, is it possible to display a message like 'page not found' or 'this website does not allow data fetching in iframes'? <!DOCTYPE html> <html> <body> <h1>Using the ...

Can the hasClass() function be applied to querySelectorAll() in JavaScript?

As a beginner in javascript and jquery, I recently attempted to manipulate classes using the following code snippet: if ($(".head").hasClass("collapsed")) { $(".fas").addClass("fa-chevron-down"); $(".fas&qu ...

creating a live updating dropdown menu using Node.js and MySQL

Upon a user clicking and selecting a client, I would like to dynamically update the region dropdown menu with options that are related to that specific client from the databaseenter code here This is my client table: Here is the Region table, where clien ...

Ways to modify client socket from JavaScript to PHP

Looking for a way to convert a client socket from JavaScript to PHP in order to receive data from the server socket? Check out the PHP socket Bloatless library here. This is an example of the Client Javascript code: <script> // connect to chat appl ...

When clicking on the dress in the masque, how do I change the attire so that it is instantly applied to the masque?

$("#tail").kendoFlatColorPicker({ preview: false, value: "#000", change: select }); $("#head").kendoFlatColorPicker({ preview: false, value: "#e15613", change: select }); I implemented the color ...

My server keeps crashing due to an Express.js API call

I'm completely new to express.js and API calls, and I'm stuck trying to figure out why my server keeps crashing. It works fine the first time, rendering the page successfully, but then crashes with the error: TypeError: Cannot read property &apo ...

I am having trouble grasping certain syntax in JavaScript when it comes to using `${method_name}`

I'm having trouble understanding some of the syntax in this code, particularly ${method_name}. I'm not sure what we are achieving by passing the method name within curly braces. global._jsname.prototype.createEELayer = function (ftRule) { if ...

As I attempt to connect with the bitcoin average server, I encounter a 403 status code error in the communication

const express = require("express"); const bodyParser = require("body-parser"); const request = require("request"); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.get("/", function(req, res){ res.sendFile(__dirname + "/inde ...