使API调用同步-> Axios调用完成

时间:2019-03-26 10:44:50

标签: reactjs redux axios synchronous

我有一个反应代码,该代码以图表格式显示从JSON格式的spyder链接中获取的图表格式的数据。有日期选择器,允许用户在API URL中传递参数。问题是新的URL调用未同步完成,因此旧数据正在图表中显示。

使用Axios调用API,并在HttpClient类中定义了getSecure()方法,该方法使用了请求承诺库。

我已经尝试过setTimeout()使API调用在UI上呈现数据之前完成,但是响应时间正在增加,而且无法预测使API等待多少时间。需要一些具体的解决方案。

因此,这里将为所有URL调用getSecure(),它不会转到下一个控制行,而是会调用URL而不等待。

const RMS_ENVIRONMENTS = ['APAC', 'EMEA', 'AMER'];
    const R = {};
    RMS_ENVIRONMENTS.map(rms_env => {
        R[rms_env] = {
            PC: `someurl?date=${cob}&region=${rms_env}&output_format=json`,
            FO: `$someurl?date=${cob}&region=${rms_env}&output_format=json`,
            MLRM: `$someurl?date=${cob}&region=${rms_env}&output_format=json`,
            RDF: `someurl?date=${cob}&region=${rms_env}&output_format=json`
        };
    });
    Object.keys(R).map(key => {
        const environment = R[key];
        Object.keys(environment).map(report => {
            const url = environment[report];
            console.log('Calling spyder for:' + url, COMPONENT);
            getSecure(url).then(detail => {
                let dataLength = _.size(detail);
                console.log(`Updated Risk Feed for ${key}, report ${report} cache with ${dataLength} records`, COMPONENT);
                Cache.updateFeeds(key, report, detail);
                //console.log('complete feed update-' + key + ' ' + report);
            })
                .catch(error => { logErr(error, COMPONENT) });
        });
    });

所以输出是:

Calling spyder for
Calling spyder for
Calling spyder for
Calling spyder for

然后

Updated Risk Feed for
Updated Risk Feed for
Updated Risk Feed for

同时,该图表将加载旧数据/半数据,然后在下面调用以获取所有数据。

Updated Risk Feed for
Updated Risk Feed for
Updated Risk Feed for

1 个答案:

答案 0 :(得分:0)

const lastIndexR = R.length - 1;  // get last index
Object.keys(R).map((key,indexR) => { // get map index
    const environment = R[key];
let lastIndexEnv = environment.length-1  // get last index of env
    Object.keys(environment).map((report,indexEnv) => { // get index of map
        const url = environment[report];
        console.log('Calling spyder for:' + url, COMPONENT);
        getSecure(url).then(detail => {
            let dataLength = _.size(detail);
            console.log(`Updated Risk Feed for ${key}, report ${report} cache with ${dataLength} records`, COMPONENT);
            Cache.updateFeeds(key, report, detail);
// check if this is the last call then update state
if(indexR === lastIndexR && indexEnv === lastIndexEnv){  
// update state true show data (initial state should be false)
// the above state will be used in render function that if state is true then 
// show data

}
            //console.log('complete feed update-' + key + ' ' + report);
        })
            .catch(error => { logErr(error, COMPONENT) });
    });
});