【问题标题】:ReactJS asynchronous global API request method, how to handle response?ReactJS 异步全局 API 请求方法,如何处理响应?
【发布时间】:2018-06-30 11:15:55
【问题描述】:

考虑到它的重复性,我正在尝试构建一个全局 API 请求函数。我遇到的问题是,尽管函数结束时 responseBody 对象不为空,但响应似乎为空?

我只能假设这部分是由于对象在更新之前被返回。

函数如下:

导出函数 restRequest(url, method, content, body) {

fetch(API_BASE_URL + url, {
    method: method,
    headers: new Headers({
        'Content-Type': content,
        'Access-Control-Request-Method': method,
        // 'Authorization': localStorage.getItem(ACCESS_TOKEN)
    }),
    body: body
}).then(
    function (response) {

        response.json().then((data) => {
            let json = JSON.parse(JSON.stringify(data));

            let responseBody = {
                code: response.status,
                body: json
            };

            //at this point the responseBody is not null

            return responseBody;
        });
    }
)
    .catch(function (err) {
        console.log('Fetch Error :-S', err);
    });

但是,如果我打电话:

    let response = restRequest('/app/rest/request', 'GET', 'application/json;charset=UTF-8', null);

响应始终为空。

处理这个问题的最佳方法是什么?

【问题讨论】:

    标签: javascript reactjs react-native react-router react-redux


    【解决方案1】:

    它是异步的,所以任何restRequest 的调用都不会立即返回responseBody = 你需要正确地链接承诺,并在restRequest 调用上调用.then。从restRequest 函数返回fetch 调用,并通过立即返回response.json() 来避免promise-callback 反模式,而不是在其中嵌套.then

    export const restRequest = (url, method, content, body) => (
      fetch(API_BASE_URL + url, {
        method: method,
        headers: new Headers({
          'Content-Type': content,
          'Access-Control-Request-Method': method,
          // 'Authorization': localStorage.getItem(ACCESS_TOKEN)
        }),
        body
      })
      .then(response => Promise.all([response.status, response.json()])
      .then(([code, body]) => ({ code, body }))
      .catch(function(err) {
        console.log('Fetch Error :-S', err);
      })
    );
    

    然后做

    restRequest('/app/rest/request', 'GET', 'application/json;charset=UTF-8', null)
      .then(response => {
        // do stuff with response. (if there was an error, response will be undefined)
      });
    

    【讨论】:

    • 在返回响应状态和正文方面,您将如何处理?谢谢,虽然这更清楚..
    • 啊,好点子 - 使用 Promise.all 来返回 status 和正文
    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多