方法在Axios返回reactjs中获取的数据之前提前返回

方法在Axios返回reactjs中获取的数据之前提前返回,reactjs,axios,next.js,Reactjs,Axios,Next.js,我正在使用axios.post方法从服务器获取数据,但它会提前返回。我使用了async和Wait,但数据没有更新 apiService.js export const getAppAuthUser = async (page, authorizedType) => { await axios.post(APIURL.apiURL, JSON.stringify({ page: page, authorized: authorizedType

我正在使用axios.post方法从服务器获取数据,但它会提前返回。我使用了async和Wait,但数据没有更新

apiService.js

export const  getAppAuthUser = async (page, authorizedType) => {

    await axios.post(APIURL.apiURL, JSON.stringify({
        page: page,
        authorized: authorizedType
    }), {
        headers: {

            'Content-Type': 'application/json'
        }
    }).then(res => {
        console.log(res);
        return res.data;
    }).catch(err => {
        console.log(err);
    });
}
component.js

import * as Users from '../api/apiService';
class User extends Component {
    sortedInfo = {};
    componentDidMount() {
        this.data=Users.getAppAuthUser(1,true);
        console.log(this.data);
    }
} 
当我安慰它时,它返回承诺{}


请帮助异步
函数就是这样做的:它们返回承诺
async/await
的存在使使用承诺的语法更容易,但它并没有改变承诺涉及的事实。要获得承诺中的值,您需要使用承诺的
。然后
方法,或者将代码放入异步函数中并等待其结果

getAppAuthUser函数中还有一个问题,即没有返回任何内容,因此承诺将解析为未定义。当您将
.then
样式与
async/await
样式混合使用时,更容易产生此类问题。我强烈建议只选择一种风格,并始终如一地使用它

export const getAppAuthUser = async (page, authorizedType) => {
  try {
    const res = await axios.post(APIURL.apiURL, JSON.stringify({
      page: page,
      authorized: authorizedType
    }), {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    console.log(res);
    return res.data;
  } catch (err) {
    console.log(err);
  }
}

import * as Users from '../api/apiService';
class User extends Component {
    sortedInfo = {};
    async componentDidMount() {
        this.data = await Users.getAppAuthUser(1,true);
        console.log(this.data);
    }
} 

JavaScript是异步的,我们不能像这样使用
this.data=Users.getAppAuthUser(1,true)
如果您希望像这样使用它,那么使用
async wait
像这样
async componentDidMount(){
this.data=await Users.getAppAuthUser(1,true);
console.log(this.data);
}

或者您可以像下面这样使用promise
Users.getAppAuthUser(1,true){
控制台日志(数据);

})

是您的权利..我们可以在setState()中使用data wait吗:-this.setState({data:wait Users.getAppAuthUser(1,true)});如果代码被一个异步函数包围,那么是的。如果我们按照这种方式处理错误,它将调用api 2次。就像api抛出坏网关一样,在这种情况下,如何处理itError处理将在catch块中进行。我模仿了您的代码并将捕获保存在getAppAuthUser中,但是如果您愿意,可以从那里删除它并在componentDidMount中执行捕获。