-1

Running following code causes apply(...) is not a function and I'm not sure why.

I feel like invoking apply for async functions not possible. What's correct way then to get apply like calling behavior?

async function throwSomething() {
  return "Apple";
}

async function caughtSomething() {
  try {
     return await throwSomething.apply(this, arguments || [])();
  } catch(e) {
     console.log(e);
  }
}

caughtSomething();
jeffbRTC
  • 1,941
  • 10
  • 29
  • 3
    Because, as the error message says, `throwSomething.apply(this, arguments || [])` isn’t a function. Why do you think this `.apply` call results in a function? This has nothing to do with `async`–`await`. Try `function f(){ return ""; }` `f.apply()();`. See the [documentation](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply). – Sebastian Simon Jun 15 '21 at 11:56
  • 1
    `throwSomething.apply(this, arguments || [])();` -> `throwSomething.apply(this, arguments || []);` or perhaps you wanted to do `throwSomething.bind(this, ...arguments)();` but I'm not sure it makes much sense. – VLAZ Jun 15 '21 at 12:11

1 Answers1

2

It is possible, you just had an extra () after throwSomething.apply(this, arguments || [])

async function throwSomething() {
  return "Apple";
}

async function caughtSomething() {
  try {
     return await throwSomething.apply(this, arguments || []);
  } catch(e) {
     console.log(e);
  }
}

caughtSomething().then(console.log);

The error says "TypeError: throwSomething.apply(...) is not a function", meaning that the return value of throwSomething.apply(...) isn't a function. If .apply wasn't a function, the error would say "TypeError: throwSomething.apply is not a function.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34