Hey I want to use a getter and setting computed property, just to make setting a value easy and then returning enriched data when it has been set.
So i'm setting the value, and then when fetching it hitting an API which will return the data, however Promise
is being returned when the value is null
on initial load of the component.
computed: {
troubleshooting: {
async get() {
if (!this.troubleshootingValue) {
return null;
}
return (await Axios.post('/api/troubleshoot', this.troubleshootingValue)).data;
},
set(value) {
this.troubleshootingValue = value;
}
}
Any idea why the initial if
isn't being hit and return null
?
CodePudding user response:
I think this is not the right approach, although if hit your if condition and return null what you are returning by calling an asynchronous function is still a promise.
CodePudding user response:
async
functions always return Promises. Your if
is being hit and returning null
, but the async
means that the value returned is a Promise that resolves to null
. If you want to be able to return a raw null
value instead of a Promise, the function can't be async
.
(Why? You could imagine an await
call happening before your if
, which means that the null
return value isn't known until the awaited promise resolves. You aren't using that capability here, but async
allows it, and it doesn't make sense to have async
have different behavior depending on the body of your function.)
This might not actually be a problem: Your implementation in the question has the nice predictable behavior of always returning a Promise, so callers don't need to check the return value to figure out whether it should behave like a Promise. In contrast, if you can sometimes synchronously return null
, callers might require an if
check or Promise.resolve()
wrapper.
That said, for an alternative that synchronously returns null
, you can either delegate to an async
function to keep using await
:
/* not async */ get() {
if (!this.troubleshootingValue) {
return null;
}
return (async () => (
await Axios.post('/api/troubleshoot', this.troubleshootingValue)).data
)();
}
Or just manually chain then
:
/* not async */ get() {
if (!this.troubleshootingValue) {
return null;
}
return Axios.post('/api/troubleshoot', this.troubleshootingValue))
.then(x => x.data);
}