Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 承诺仍然挂起,即使使用.then()_Javascript_Reactjs_Asynchronous_Promise - Fatal编程技术网

Javascript 承诺仍然挂起,即使使用.then()

Javascript 承诺仍然挂起,即使使用.then(),javascript,reactjs,asynchronous,promise,Javascript,Reactjs,Asynchronous,Promise,我正在使用axios从后端检索数据,但承诺仍在等待中 我使用了.then()甚至异步和等待。我使用的是.then(res=>res.data),因为我知道每个承诺都有保存检索到的数据的“data”键,之后它将以这种方式返回。我还绑定了构造函数中的函数 async getTrackInfo() { return await axios.get('http://localhost:60231/api/values') .then(res => res.data); }; com

我正在使用axios从后端检索数据,但承诺仍在等待中

我使用了.then()甚至异步和等待。我使用的是.then(res=>res.data),因为我知道每个承诺都有保存检索到的数据的“data”键,之后它将以这种方式返回。我还绑定了构造函数中的函数

async getTrackInfo() {
  return await axios.get('http://localhost:60231/api/values')
    .then(res => res.data);
};


componentDidMount() {
  const data = this.getTrackInfo();
  console.log(data);

  this.setState({
    tracks: data
  });
}

但不幸的是,它返回的是未定义的。

以下代码可以工作:-

async getTrackInfo() {
  return await axios.get('http://localhost:60231/api/values')
    .then(res => res.data);
};


async componentDidMount() { // Make this function async
  const data = await this.getTrackInfo(); // add await here
  console.log(data);

  this.setState({
    tracks: data
  });
}

您需要
const data=wait this.getTrackInfo()
async
函数始终返回承诺。承诺是管理异步操作的标准方式
async
/
await
提供了用于管理它们的过程式语法。它们不会阻止异步操作的执行asynchronous@ChrisG-那会出错的
componentDidMount
不是
async
@Quentin非常确定将
componentDidMount()
更改为
async
的指令隐含在Chris的评论中……要使用
Wait
,您必须使函数(在这种情况下,
componentDidMount
是异步的。一个小挑剔,
返回等待
中的
等待
是多余的。还可以从
getTrackInfo()
中删除
async
,并
返回axios…
。它也会做同样的事情。