Skip to content

Need help converting code to callback function or async/await #2891

@garrett16r

Description

@garrett16r
  • Node.js Version: 12.16.1
  • OS: Windows 10 Home
  • Scope (install, code, runtime, meta, other?): Code
  • Module (and version) (if relevant): N/A

Code:
(This function simply needs to be called in another file to retrieve an ID from an SQL database (the SQL part works perfectly fine, nothing to worry about there) and return the ID for use in that other file.)

let getChannel = (chanType) => {
  var chanID; // Value that needs to be assigned and returned to var that called the function in another file

  db.getConnection((err, con) => {
    con.query(`SELECT * FROM channels WHERE type = '${chanType}'`, (err, rows) => {
      if (err) throw err;

      chanID = rows[0].id;

      // Still holds value here
      con.release();
    });
  });
  return chanID; // reverts to undefined here
}

The code that I have right now has the problem of always returning chanID as undefined. From some research I did, I found that it has to do with the asynchronous nature of node.js, and that concept makes sense. The part of the code that actually reassigns the value of chanID is being executed too late because of all the asynchronous stuff, that much is simple enough.

Basically, I need to convert this code into a setup with either a callback or using async/await. I'm fairly new to Javascript and node.js though, so I'm having a lot of trouble figuring out how to actually do that. Every example I've found on how to do this uses really simple functions that just don't really carry over to what I'm trying to with having multiple nested functions, etc. I'd really appreciate some pointers on how I can apply the concepts of callbacks or async await to this code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions