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:
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")
}
CodePudding user response:
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");
}
CodePudding user response:
With your second example you are returning a function, not the result of the function. Store the function in an object and call the function:
const list = () => {
return (async () => await api.get("list"))();
}
CodePudding user response:
You are returning the function res in the second case, not the output of res. You can use an IIFE to return the value of res as wanted:
const list = () => {
return api.get("list")
}