I am having trouble returning a value to an outermost function from an async
call. The object is part of a step for the React-Simple-Chatbot and I am attempting to use the validator function. It accepts one value, a string
from user input. I need to return either true or a string
to the validator to make it work. I cannot figure out how to get my function and/or callback to return the data to the validator.
let p;
{
id: 'productTypes',
user: true,
validator: function(value) {
response(value, this.id, function(answer){
return p
})
},
trigger: ({value}) => value.toLowerCase() === 'back' ? 'back' : 'productDetails'
}
function response(value, id, callback) {
getData(value, id).then(x => p = x.data).then(x => callback(x))
}
function getData(value, id) {
return axios.get('http://localhost:8085/chatbot', {params: {value: value, func: id }})
}
I've also attempted to resolve this issue using async/await
. The problem with this is that the initial value of p
being returned to validate
is undefined
but subsequent calls to the validate
function work. I'm not sure why return p
is being run before response(value, this.id)
.
{
id: 'productTypes',
user: true,
validator: function(value) {
response(value, this.id);
return p;
},
trigger: ({value}) => value.toLowerCase() === 'back' ? 'back' : 'productDetails'
},
async function response(value, id) {
let data = await getData(value, id);
p = data.data;
}
function getData(value, id) {
return axios.get('http://localhost:8085/chatbot', {params: { value: value, func: id }})
}