首页 文章

如何让Promise的反应机构做出反应?

提问于
浏览
0

在我的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;
}

上面的代码片段是在Saga中实现apiCall . 如果响应代码为403,则它可以触发auth流程 .

但我不知道如何处理案例200的响应 . 我可以看到它返回一个Promise,但是在getData函数中我的console.log没有打印任何东西(或者说它没有被执行) .

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

1 回答

  • 0

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

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

相关问题