0

OK, I am using Objection.js to handle some database stuffs with node.js
I know that the error I am getting is common to someone learning how to use async functions, but I just cant seem to get this to work right. My async function is returning something before it finishes the query (i think)

async function getStatusSensor() {
const sensors = await StatusSensor.query()
.select('*').limit(1)
var sensor = sensors[0]
console.log(sensor.monitor + " from function")
console.log(sensor.status_type + " from function")
return sensor;
}

const sensor = getStatusSensor()
console.log(sensor.monitor)
console.log(sensor.status_type)

and the results that I get look like this

undefined
undefined
3957b from function
20GPSChadsCtrl from function

So that I can only operate on the returned row within the function that queried it. What I am after is a simple async function that I can call just to get a particular row from a database. thanks for any help!

skrite
  • 317
  • 4
  • 18
  • Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Estus Flask Oct 02 '18 at 18:50

1 Answers1

1

Since getStatusSensor is marked async, it will return a promise that you have to wait for to get resolved before you can use the result.

Either like so (if you're calling it from another async function):

const sensor = await getStatusSensor();

Or like so:

getStatusSensor().then(sensor => {
  console.log(sensor.monitor)
  console.log(sensor.status_type)
});
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • The second line worked, but the first did not. I am a little confused because i thought the first was another async function – skrite Oct 02 '18 at 19:31
  • I guess, if I wanted to use your first example , calling from another async function, how would I change that function? thanks – skrite Oct 02 '18 at 20:02
  • 1
    @skrite an `async` function is one that is marked with the `async` keyword :D – robertklep Oct 03 '18 at 07:27