how correctly make db flow in node.js

I'm newbies in node.js world, so my question can be strange for you. I have very easy scenario: 1) insert row in db, get ID for this row 2) insert multiply rows, each of them uses ID which we get previously

There are problems with flow... stage 2 is started before we get response from stage 1 or all stages are finished (connection.end() is called) before we finished insertion.

I tried to use async module, however it doesn't help me Let's see at code:

// open connection

conn.query('INSERT INTO receipt SET ?', {postid: postGUID, body: body}, function(err, result) {
    if (err) throw err;
        console.log("ID: "+result.insertId );

    conn.query('INSERT INTO imgs SET ?', {postid: result.insertId, link: imgSrc}, function(err, result) {
        if (err) throw err;

    });
});

conn.end( function(err) {
    console.log("CLOSE CONNECTION"); 
    console.log(err);
});

could you help me with it please?

Since conn.query is most likely asynchronous you are closing your connection before it's finished querying. A quick fix could be the following.

conn.query('INSERT INTO receipt SET ?', {postid: postGUID, body: body}, function(err, result) {
    if (err) throw err;
        console.log("ID: "+result.insertId );

    conn.query('INSERT INTO imgs SET ?', {postid: result.insertId, link: imgSrc}, function(err, result) {
        if (err) throw err;

       conn.end( function(err) {
          console.log("CLOSE CONNECTION"); 
          console.log(err);
       });
   });
});

A better fix is probably to close the connection when the process ends.