How to control the response order of a database query with JavaScript

I have two nested database queries:

db.query(query1, function (err, rows, fields) {
    if (!err) {
        console.log("outer rows.length: " + rows.length);

        function outer() {
            for (var i = 0; i < rows.length; i++) {
                console.log(i + ". outer row");

                function inner() {
                    db.query(query2 + i + 1, function (error, r, f) {
                        if (!error) {
                            for (var j = 0; j < r.length; j++) {
                                console.log(j + ". inner row");
                            }
                        }
                    });
                };
                inner();
            }
        }
        outer();
    }
});

I expect the log order to be...

outer rows.length: 2
0. outer row
0. inner row
1. inner row
1. outer row
0. inner row

However I get this result:

outer rows.length: 2
0. outer row
1. outer row
0. inner row
1. inner row
0. inner row

There are two inner rows which belong to 0. outer row und one inner row which belongs to 1. outer row. This code first logs all the outer rows, then all the inner rows.

I´m looking for a way to prevent this. I think, the issue lies in the asynchronicity of the code. I have tried to fix it by putting function inner() into an immediately invoking function with the style ( function inner() { .. } )();, but this did not change anything. How can I determine that each inner row will be logged right after its corresponding outer row, just like in the first list? Any advice would be appreciated.

Edit:

It´s server-side JavaScript in Node.js using the node-mysql module.

It definitely is the Asynchronous feature of NodeJS aefecting your code, you need to create a callback in your query that will then output the response after your query is finished if you want to have this be asynchronous (Which you probably do)

There are great examples of this on the NodeJS website on how to do ansychronous calls with callbacks.

here is an example:

function formSubmit(submitEvent) {
  var name = document.querySelector('input').value
  request({
    uri: "http://example.com/upload",
    body: name,
    method: "POST"
  }, postResponse)
}

function postResponse(err, response, body) {
  var statusMessage = document.querySelector('.status')
  if (err) return statusMessage.value = err
  statusMessage.value = body
}

exports.submit = formSubmit