Run a Function Stored in an Object

Viewed 57

I have created an object with the ES6 documentation, and have been successful! However, when I attempt to call the functions by doing shardHandler('help') or such, the console shows Promise { <pending> } but the 1, 2, 3, 4, etc. is never called.

Below is my code. How can I call the functions from inside the object?

const shardHandler = async (arg) => ({
  "ids": (client, message) => {
    console.log('1')
  },
  "respawn": (client, message) => {
    console.log('2')
  },
  "kill": (client, message) => {
    console.log('3')
  },
  "restart": (client, message) => {
    console.log('4')
  },
  "help": (message) => {
    console.log('5')
  }
})[arg] || "help";
const run = async () => shardHandler('kill');
run()
1 Answers

You have several problems here.

First, calling shardHandler returns a Promise because it is an async function. So if you want to access one of the functions you define within your object, you'll have to await the promise.

const shardHandler = async (arg) => ({
  "kill": (client, message) => {
    console.log('3')
  },
})[arg]

const run = async () => {
  const result = await shardHandler('kill')
  result()
}

run()

Then I also see that you are trying to default to returning "help" if no argument was provided to shardHandler but the way you wrote won't work that way : you're just resolving to the actual string "help" and not the function. Here are ways to do it:

const shardHandler = async (arg) => ({
  // ...
})[arg || "help"];
const shardHandler = async (arg = "help") => ({
  // ...
})[arg];

Then, unless there is some specific reason you aren't showing here (which could be totally appropriate because one must simplify their problem before posting!), shardHandler doesn't need to be a function: just make it an object.

const shardHandler = {
  "ids": (client, message) => {
    console.log('1')
  },
  "respawn": (client, message) => {
    console.log('2')
  },
  "kill": (client, message) => {
    console.log('3')
  },
  "restart": (client, message) => {
    console.log('4')
  },
  "help": (message) => {
    console.log('5')
  }
}
const run = () => shardHandler['kill']()

And finally, the async keywords seem oddly placed. It's hard to know for sure without a more complete version of the code but be careful there. Calling an async function always returns a Promise which you then have to handle with await from within another async context, or with .then() to get the actual "desired" output.

Related