3

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)
  } 

...

2 Answers2

4

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);
  };

  // ...
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
0

In your current code, the problem is that makeQuery() is requesting to the URL but not waiting for the response from the URL. You need to make makeQuery() also an async/await function.

var request = require('request');

const makeQuery = async (query) => {
  return new Promise((resolve, reject) => {
    request("http://0.0.0.0:4000/wikiweb?text=" + query, function (error,response,body) {

      if (error) {
        reject(error);
      }
      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)
    // await this.setState({data : response, loaded : true});
    // console.log(this.state.data)
  }
}
Sujil Maharjan
  • 1,307
  • 10
  • 12