Moving code to an exported function results in TypeError: Converting circular structure to JSON

Alex Ironside

I am using express and mysql packages to just test out queries.

I had this code:

connection.connect();

connection.query('SELECT 1 + 1 AS solution', (error, results) => {
  if (error) {
    connection.end();
    console.log('error');
    throw error;
  }
  connection.end();
  console.log(results);
  return results;
});

And it works just fine. But when I move it to a different file and try to export it like this:

query.js

const connection = require('../config/connection');

connection.connect();

module.exports = async (query) => connection.query(query, (error, results) => {
  console.log(query);
  if (error) {
    // connection.end();
    console.log('error');
    throw error;
  }
  // connection.end();
  console.log(results);
  return results;
});

app.js

try {
  const queryResult = await query('SELECT 1 + 1 AS solution');
  console.log(queryResult, 2);
  res.send(queryResult);
} catch (err) {
  console.log(err);
}

I get this error:

TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at stringify (C:\Users\aironsid\Documents\tatooify\server\node_modules\express\lib\response.js:1119:12)
at ServerResponse.json (C:\Users\aironsid\Documents\tatooify\server\node_modules\express\lib\response.js:260:14)
at ServerResponse.send (C:\Users\aironsid\Documents\tatooify\server\node_modules\express\lib\response.js:158:21)
at app.get (C:\Users\aironsid\Documents\tatooify\server\app.js:44:9)
at process._tickCallback (internal/process/next_tick.js:68:7)

Also in console logs I get, a big object followed by number 2, then I get the errthe ``or, then I get the query value, and then the result. Like so:

Big object 2

error

SELECT 1 + 1 AS solution

[ RowDataPacket { solution: 2 } ]

So what this tells me is that my code runs in async. Removing async/await from both files doesn't change anything. So my code first runs the app.js code, then the query.js code, which takes some time. But why? And how can I make it wait? connection.query() does not return a promise.

aljazerzen

Problem is that your async function does not wait for query to finish.

It should return a promise that resolves when the query completes, but instead returns promise that immediately resolves into return value of function connection.query().

You should change that to:

module.exports = (query) => {

    return new Promise(resolve => 
        connection.query(query, (error, results) => {
          console.log(query);
          if (error) {
            // connection.end();
            console.log('error');
            throw error;
          }
          // connection.end();
          console.log(results);
          resolve(results);
        })
    );

}

With omited commented lines and shorter syntax:

module.exports = (query) => new Promise((resolve, reject) => 
  connection.query(query, (error, results) => {
    if (error) return reject(error);

    resolve(results);
  })
);

And even shorter:

module.exports = (query) => 
  new Promise((resolve, reject) => 
    connection.query(query, (error, results) => 
      error ? reject(error) : resolve(results)
  )
);

To clarify: your async keyword did not have any effect, because what it does is allow you to use await in its function and wraps whatever you return into a promise.

You did not use any awaits and immediately returned result via lambda function.

Note that your return statement returned from callback passed to connection.query function and not from the main function.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Chrome sendrequest error: TypeError: Converting circular structure to JSON

TypeError: Converting circular structure to JSON in nodejs

TypeError: Converting circular structure to JSON when trying to POST request

VM1374:32 Uncaught TypeError: Converting circular structure to JSON(…)

Doing a proper MongoDB Query (TypeError: Converting circular structure to JSON)

TypeError converting circular structure to json at JSON.stringify (<anonymous>)

TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest'

Angular - TypeError: Converting circular structure to JSON

Firestore references create a "TypeError: Converting circular structure to JSON"

Express Middleware: ERROR: TypeError: Converting circular structure to JSON

Elliptic : TypeError : Converting circular structure to JSON

[Vue warn]: Error in render: "TypeError: Converting circular structure to JSON

ERROR TypeError: Converting circular structure to JSON --> starting at object with constructor 'FormGroup'

TypeError: Converting circular structure to JSON property 'name' closes the circle

How do I solve "TypeError: Converting circular structure to JSON" in NodeJS

TypeError: Converting circular structure to JSON with StorybookJS on React Native

avoiding TypeError: Converting circular structure to JSON

TypeError: Converting circular structure to JSON - find error in json

Amazon Cognito confirmPassword fails with (TypeError: Converting circular structure to JSON)

GraphCool TypeError: Converting circular structure to JSON

how to solve (Uncaught TypeError: Converting circular structure to JSON)

Uncaught TypeError: Converting circular structure to JSON after Angular / dependencies update

TypeError: Converting circular structure to JSON in retrieving html string from mongodb

Sequelize: TypeError: Converting circular structure to JSON

Reading fixture is throwing error TypeError: Converting circular structure to JSON

TypeError: Converting circular structure to JSON -- Next.js

"TypeError: Converting circular structure to JSON" with GET request

"TypeError: Converting circular structure to JSON" with GET request

Axios TypeError: Converting circular structure to JSON