如何使用API​​调用中的axios在React中使用异步等待

时间:2019-01-10 08:54:40

标签: javascript reactjs redux async-await react-redux

我是Web开发的新手。我正在使用df = pd.DataFrame(np.random.randn(5,5)) print(df) pd.set_option('precision',10) print(df) 。因此,在这里,我想将react.js用于API调用。我正在使用async/await

现在

我有什么像

axios

我的邮政服务就像

export function fetchToken(bodyjson) {
  return (dispatch) => {
    let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
    return post(url, bodyjson)
      .then((response) => {
        if (response.status === 200) {
          localStorage.setItem('user', bodyjson.userName);
          localStorage.setItem('access_token', response.payload.access_token);
          history.push('/');
          dispatch({
            type: LOGIN_SUCCESS,
            data: response.payload,
          })
        }
        else {
          dispatch({
            type: LOGIN_FAILED,
            data: response.status,
          });
        }
      })
  }
}

现在,我想在这里使用异步等待。我对此感到非常困惑。我已经看了很多教程。  我想在export const post = (url, post_data) => axios.post( apiGatewayEndpoint.apiGatewayEndpoint + url, post_data, { headers: { "Authorization": localStorage.getItem("access_token") !== null ? `Bearer ` + localStorage.getItem("access_token") : null, "Content-Type": "application/json" } } ).then(data => { if (data.status === HttpStatus.OK) { return { status: data.status, payload: data.data }; } }).catch(err => { return { status: err.response.data, payload: null }; }); 之后立即调用API。在此基础上,我想将用户重定向到差异页面。

所以,有人可以帮我这个login

谢谢:-)

现在我正在使用它,

async-await

2 个答案:

答案 0 :(得分:1)

对于获取请求,您可以使用params发送数据等。

   export const getData = async () => {
    try {
        const { data } = await axios({
            method: 'get', //you can set what request you want to be
            url: `yoururl`,
            params: {
            // key values pairs   
            }
            headers: {
                'token': token
            }
        });
        // run some validation before returning
        return data;
    } catch (e) {
        console.log(e);
        return .. some error object;
    }
};

用于发帖请求

export const getData = async (params) => {
    try {
        const { data } = await axios({
            method: 'post', //you can set what request you want to be
            url: `url`,
            data: params,
            headers: {
                'x-auth-Token': token
            }
        });
        // run some validation before returning
        return data;
    } catch (e) {
        console.log(e);
        return .. some error object;
    }
};

错误对象示例

{
  status: 'error',
  message: 'failed with something'
}

然后您可以调用任何这样的api

async componentDidMount() {
 const data = await getData();
 if(data.status === 'Something') {
// do something    
  }
}

答案 1 :(得分:1)

为此,您确实不需要异步等待。

采用然后连锁的方法

export function fetchToken(bodyjson) {
    return (dispatch) => {
        let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
        return post(url, bodyjson)
        .then((response) => {
            if (response.status === 200) {
                localStorage.setItem('user', bodyjson.userName);
                localStorage.setItem('access_token', response.payload.access_token);
                history.push('/');
                dispatch({
                    type: LOGIN_SUCCESS,
                    data: response.payload,
                })
                //next api call
                return post(newUrl, newBodyjson)
            }
            else {
                dispatch({
                    type: LOGIN_FAILED,
                    data: response.status,
                });
            }
        })
        .then((newApiResponse) => {
            //Do stuffs with new api response
        })
    }
}

但是,如果您只想使用 async-await 方法

export function fetchToken(bodyjson) {
    return async (dispatch) => {
        let url = LOGIN_PATH + "username=" + bodyjson.userName + "&password" + "=" + bodyjson.password;
        let response = await post(url, bodyjson)
        if (response.status === 200) {
                localStorage.setItem('user', bodyjson.userName);
                localStorage.setItem('access_token', response.payload.access_token);
                history.push('/');
                dispatch({
                    type: LOGIN_SUCCESS,
                    data: response.payload,
                })
                let newApiResponse = await post(newUrl, newBodyjson)
                //Do stuffs with new api response
            }
            else {
                dispatch({
                    type: LOGIN_FAILED,
                    data: response.status,
                });
            }
    }
}