【问题标题】:How to get response body from a Promise in react?如何从 Promise 中获取响应体?
【发布时间】:2017-09-19 20:58:46
【问题描述】:

在我的 React 应用程序中,我使用 fetch 从服务器端检索一些图表数据。 如下所示,函数fetchData负责获取json格式的图表数据。我可以在 Chrome 的网络面板中看到呼叫成功。

function fetchData () {
    let token;
    if (sessionStorage.bearerToken) {
        token = `Bearer ${sessionStorage.bearerToken}`;
    }
    console.log('the token is', token);
    const config = {};
    config.method = 'GET';
    config.headers = {
        'Content-Type':'application/json',
        'Authorization':token
    };
    const req = new Request(webConfig.ReqURL.fetchChartsData, config);
    // return fetch(`${config.base}dashboard_charts.json`)
    return fetch(req)
    .then((response) => {
        return response;
    });
}

function * getData (action) {
    try {
        // const charts = yield call(fetchData);
        const resp = yield apiCall(fetchData);
        const charts = resp.then((resp) => { return resp.json(); });
        console.log('the charts....', charts);
        yield put({ type: UPDATE_DASHBOARD_CHART, charts: charts });
    } catch (error) {
        yield put({ type: UPDATE_DASHBOARD_CHART, charts: [] });
    }
}

我需要添加http响应状态码检查。如果状态码是 403,那么我需要应用程序重定向到登录流程。这就是我直接使用 apiCall(fetchData) 而不是 call(fetchData) 的原因。

export function* apiCall(fn, ...rest) {
    const response = yield call(fn, ...rest);
    const status = response.status;
    console.log('~~ status', status);
    if(status === 419) { //419: When the session has expired
        yield put(sessionExpired());
    }
    if(status === 403) { //403: When the resource is forbidden
        // yield put(resourceForbidden());
        yield auth();
        return Promise.reject(response);
    }
    if(status === 401) { //401: When the resource is unauthorized
        yield put(resourceUnauthorized());
    }

    return response;
}

上面的代码sn-p是一个Saga中apiCall的实现。如果响应代码是 403,它可以触发身份验证流程。

但我不确定如何处理案例 200 的响应。我可以看到它返回了一个 Promise,但在 getData 函数中,我的 console.log 没有打印任何内容(或者说它没有执行)。

我可以知道我的代码有什么问题吗?

【问题讨论】:

    标签: reactjs promise redux-saga


    【解决方案1】:

    response.json() 是一个承诺,应该用 then 来处理。以下代码应该可以工作:

    resp.then(resp => resp.json())
    .then(json => {
        yield put({ type: UPDATE_DASHBOARD_CHART, charts: json });
    });
    

    【讨论】:

      猜你喜欢
      • 2017-12-28
      • 2020-08-27
      • 2020-08-10
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 2013-03-14
      相关资源
      最近更新 更多