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

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

这是函数:

导出函数restRequest(URL,方法,内容,正文){

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


响应始终为空。

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

最佳答案

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

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

09-18 04:56