This question already has answers here:
How do I return the response from an asynchronous call?

(42个答案)


2年前关闭。




当前,console.log()中的makeQuery()返回正确的对象,而console.log()中的scoop()返回“未定义”,因为response中的scoop()的定义不等待对makeQuery()的函数调用返回。

我想让response中的scoop()定义在下面的代码运行之前等待对makeQuery()的函数调用。

我如何做到这一点?
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)
  }

...

最佳答案

您必须从makeQuery函数返回一个promise,否则就没有使用await的promise,它将立即解决。

示例

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

  // ...
}

10-05 20:50