0

I have the following code to get me some information from my database:

  const getDeviceUID = `SELECT Device_UID FROM Device WHERE ThingName = "${deviceName}"`;

  const deviceUIDResult = await new Promise((resolve) => {
    connection.query(getDeviceUID, (err, results, fields) => {
       if (err) return resolve(false);
       resolve(results);
     });
  });

I'm assuming (I'm pretty new to this!) that deviceUIDResult is now a JSON object as when I do this:

console.log("RES: " + JSON.stringify(deviceUIDResult));

I get the following:

RES: [{"Device_UID":"xxxx-xxxx-xxxx-xxxx"}]

But when I try to parse it:

  deviceUIDObj = JSON.parse(deviceUIDResult)

I get this:

SyntaxError: Unexpected token o in JSON at position 1

And when I try to extract my field:

var myField = deviceUIDResult["Device_UID"];

it tells me that its undefined. What am I not understanding here?

Cornel Verster
  • 1,664
  • 3
  • 27
  • 55
  • 3
    *"What am I not understanding here?"* `JSON.parse` takes in a string containing JSON and converts it to native JavaScript value. `deviceUIDResult` is already a JavaScript array. – Felix Kling Dec 10 '18 at 19:39
  • You don't need to parse it, in other words. – Pointy Dec 10 '18 at 19:41
  • Also your Promise callback should have *two* parameters, the second being the `reject()` link. Call that when `err` is non-empty instead of `resolve()`. – Pointy Dec 10 '18 at 19:41
  • Also, check your database API because it's likely the case that `connection.query()` can itself return a Promise, and if so you don't need to make your own. – Pointy Dec 10 '18 at 19:43

1 Answers1

2

deviceUIDResult is a JavaScript array containing one object. Note the square braces:

indicates an array 
↓
[{"Device_UID":"xxxx-xxxx-xxxx-xxxx"}]
 ↑
 indicates an object

So, get the first object in the array first: var myField = deviceUIDResult[0]["Device_UID"];