The only way to work with results of an asynchronous function call is to make the function that executes the async call also asynchronous, i.e. it has to return a promise.
Think of it this way: axios.post
promises to isAbstractSubmitted
:
“I'll set isSubmitted
for you some day, pinky swear.”
So isAbstractSubmitted
would have to return that promise to whatever is calling it – it's not able to return any actual value, because it's only been promised to get a value:
function isAbstractSubmitted(proposal_id, version) {
return axios.post('{{ url("irb/issubmitted") }}',
{
proposal_id: proposal_id,
version: version
},
{
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
.then(function (response) {
return response.data.submitStatus
})
.catch(function (error) {
console.log(error);
});
}
Any code invoking isAbstractSubmitted
will have to deal with the promise, like this, for example:
isAbstractSubmitted('my_proposal_id', 'my_version').then(
function (submitStatus) {
if (submitStatus === 'OK') {
console.log('abstract has been submitted');
} else {
console.log('abstract has not been submitted');
}
}
)
Once you are in “promise land”, there is no way out of it, all subsequent code relies on the promises made before.
There is, however, a way to change the code so that it at least looks like the familiar synchronous code, namely async/await:
async function isAbstractSubmitted(proposal_id, version) {
let response = null;
try {
response = axios.post('{{ url("irb/issubmitted") }}',
{
proposal_id: proposal_id,
version: version
},
{
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
} catch (error) {
console.log(error);
return false;
}
return response ? response.data.submitStatus : null
}
var submitStatus = await isAbstractSubmitted('my_proposal_id', 'my_version')
if (submitStatus === 'OK') {
console.log('abstract has been submitted');
} else {
console.log('abstract has not been submitted');
}
By adding the async keyword to your function, you automatically make it return a promise, but it looks like it's actually returning the promised value.
You can add await to any function call that returns a promise to get the promised value.