Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS Arrow fuinction returns self not function

In React I’m using utility functions to handle the api calls. When the Arrow function is no longer anonymous it returns a pending promise, which is what I would like. However when the arrow function is anonymous it returns the function.

Is there any way to return a pending promise in one line?

Here is what the function looks like when not anonymous:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const list = () => {
    let res = async () => await api.get("list");
    return res();
}

Here is what it looks like anonymous:

const list = () => {
    return async () => await api.get("list")
}

>Solution :

Because you’re just returning the function, not executing it. This executes the function:

res();

Nowhere in the second example do you have that additional set of parentheses to execute it. Add them:

const list = () => {
  return (async () => await api.get("list"))();
}

Or, even simpler, don’t wrap the operation in an unnecessary function in the first place:

const list = () => {
  return api.get("list");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading