Currently, the console.log() in makeQuery() is returning the correct object while the console.log() in scoop() is returning "undefined" as the definition of response in scoop() is not waiting for the function call to makeQuery() to return.
I would like for the definition of response in scoop() to wait for the function call to makeQuery() before the code below runs.
How do I make this happen?
var request = require('request');
const makeQuery = (query) => {
request('http://0.0.0.0:4000/wikiweb?text=' + query, function (error, response, body) {
var jason = JSON.parse(body)
console.log(jason)
return jason
}
)
class Wiki extends React.Component {
constructor (props) {
super(props)
this.scoop = this.scoop.bind(this);
this.state = {loaded: false}
}
scoop = async (e) => {
e.preventDefault();
var query = this.textInput.value;
var response = await makeQuery(query);
console.log(response)
// await this.setState({data : response, loaded : true});
// console.log(this.state.data)
}
...
You have to return a promise from the makeQuery function or there will be no promise to use await on and it will resolve immediately.
Example
const makeQuery = query => {
return new Promise(resolve => {
request("http://0.0.0.0:4000/wikiweb?text=" + query, function(
error,
response,
body
) {
var json = JSON.parse(body);
console.log(json);
resolve(json);
});
});
};
class Wiki extends React.Component {
constructor(props) {
super(props);
this.scoop = this.scoop.bind(this);
this.state = { loaded: false };
}
scoop = async e => {
e.preventDefault();
var query = this.textInput.value;
var response = await makeQuery(query);
console.log(response);
};
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With