Home > Software design >  Why does the Javascript function return right away even with await?
Why does the Javascript function return right away even with await?

Time:06-21

I'm newer to JavaScript and struggling to understand why this function just returns right away, even though I added an await. The code below is the minimal example to replicate what I am attempting to do. When I call add_user() from add(), id is undefined because add_user() is returning right away instead of waiting for completion of the query. I added the console log to verify that row.id is the value I expected (i.e. 1).

'use strict';

import sqlite3 from 'sqlite3'
import { open } from 'sqlite';

async function add_user(value) {
   await (async () => {
      const db = await open({
         filename: dbFile,
         driver: sqlite3.Database
      })

      const row = await db.get(`SELECT id FROM Users WHERE name LIKE "${value}"`)
      console.log(row.id)
      return row.id
   })()
}

async function add(req, res) {
    var id = await add_value(req.body.value)
    console.log(id)
}

CodePudding user response:

I'm pretty sure the code is running asynchronously as desired - it's just that you aren't returning anything from add_user. For a smaller example:

async function someFn() {
  await somePromise;
}

Above, someFn will always return a Promise that resolves to undefined, because nothing was returned from someFn. You're running into the same issue.

Use instead

async function add_user(value) {
   const db = await open({
       filename: dbFile,
      driver: sqlite3.Database
   })
   const row = await db.get(`SELECT id FROM Users WHERE name LIKE "${value}"`)
   console.log(row.id)
   return row.id
}
  • Related