【问题标题】:Is there a way to refactor dependend Axios calls to an JSON api?有没有办法将依赖 Axios 调用重构为 JSON api?
【发布时间】:2019-07-29 09:25:15
【问题描述】:

我目前正在尝试从 JSON api 端点接收数据并进一步处理它们。主要目标是将包含所有数据的 json 文件归档为单独的数组,并将其转换为 4 个不同的 CSV 文件。正如您在下面的代码中看到的那样,我成功接收数据,但由于对 api 的依赖调用,我有时会遇到早期调用失败以及更深入调用失败的问题。

我的问题是:有没有办法成功地重构它以捕获失败的调用并重新运行它们,并且有一个想法可以使它更可靠和“更干净”

const axios = require('axios')
const fs = require('fs')
const colors = require('colors')

const url = "json.endpoint.url";
const MANDATOR = 1234567890

const TecDoc = []


async function callApi(url, query) {
    let res = await axios.post(url, query);
    let { data } = res.data
    return data.array
}


const getManufacturer = { "getManufacturers": {"country": "DE", "favourdedList": 0, "lang": "de", "linkingTargetType": "P", "provider": MANDATOR} }
let Manufacturer = callApi(url, getManufacturer)
Manufacturer.then(function(ManufacturerResult) {
    for(let i = 0; i < ManufacturerResult.length; i++) {


        var getModelSeries = { "getModelSeries": {"country": "DE", "favourdedList": 0, "lang": "de", "linkingTargetType": "P", "manuId": ManufacturerResult[i].manuId, "provider": MANDATOR}}
        let Model = callApi(url, getModelSeries)
        Model.then(function(ModelResult) {
            if(ModelResult !== undefined) {

                for(let j = 0; j < ModelResult.length; j++) {

                    var getVehicleIdsByCarCriteria = { "getVehicleIdsByCriteria": {"carType": "P", "countriesCarSelection": "DE", "lang": "de", "manuId": ManufacturerResult[i].manuId, "modId": ModelResult[j].modelId, "provider": MANDATOR}}
                    let Car = callApi(url, getVehicleIdsByCarCriteria)
                    Car.then(function(CarResult) {
                        for(let k = 0; k < CarResult.length; k++) {


                            var getVehicleByIds4 = { "getVehicleByIds4": {"articleCountry": "DE", "axles": false, "cabs": false, "carIds": {"array": [CarResult[k].carId]}, "countriesCarSelection": "de", "country": "de", "countryGroupFlag": false, "kbaData": true, "lang": "de", "motorCodes": false, "provider": MANDATOR, "secondaryTypes": false, "wheelBase": false}}
                            let finalCarData = callApi(url, getVehicleByIds4)
                            finalCarData.then(function(Result) {

                                //console.log(Result[0].vehicleDetails.manuName)
                                TecDoc.push(Result)

                                fs.writeFile('data.json', JSON.stringify(TecDoc), 'utf-8', function() {
                                    console.log("Writing: " + Result[0].vehicleDetails.manuName + " - " + Result[0].vehicleDetails.modelName + " ( " + Result[0].vehicleDetails.typeName + " ) ")
                                })

                            }).catch(function(error) {
                                console.log("FinalCar: ".bold + `${error}`.bgBlue)
                            })


                        }
                    }).catch(function(error) {
                        console.log("CarType: ".bold + `${error}`.bgYellow.black)
                    })   


                }
            }
        }).catch(function(error) {
            console.error("ModelSeries: ".bold + `${error}`.bgMagenta)
        })


    }
}).catch(function(error) {
    console.error("Manufacturer: ".bold + `${error}`.bgRed)
})

//CSV.writeRecords(TecDoc).then(() => console.log('✔ ' + 'The Manufacturer CSV file was successfully written'))

【问题讨论】:

    标签: node.js json api refactoring axios


    【解决方案1】:

    在这种情况下,您需要通过创建一些返回 Promises 的单独函数来模块化您的代码。取一个数组并将该函数调用推送到循环中。让我们看一下这个例子。

    // You have requirement to get data from func1 => func2 => func3. If any of once is rejected then throw an error or getting success
    const userUtils = {};
    
    userUtils.function1 = (yourInputs) => {
    return new Promise((resolve, reject) => {
    if (yourInputs) {
      return resolve('f1');
    }
    return reject();
    });
    };
    
    userUtils.function2 = (fun1Output) => {
    return new Promise((resolve, reject) => {
    if (fun1Output) {
      return resolve('f2');
    }
    return reject();
    });
    };
    
    userUtils.function3 = (fun2Output) => {
    return new Promise((resolve, reject) => {
    if (fun2Output) {
      return resolve('f3');
    }
    return reject();
    });
    };
    
    userUtils.allFunctionCall = async (input) => {
    try {
    const resultf1 = await userUtils.function1(input);
    const resultf2 = await userUtils.function2(resultf1);
    const resultf3 = await userUtils.function3(resultf2);
    return resultf3;
    } catch (error) {
    console.log(error);
    throw error;
    }
    };
    
    userUtils.callFunctions = () => {
    const array = [];
    for (let i = 0; i < 1; i += 1) {
    // call function here 
    array.push(userUtils.allFunctionCall(true));
    }
    
    Promise.all(array)
    .then((res) => {
      console.log('RES', res);
    })
    .catch((err) => {
      console.log(err);
    });
    };
    
    userUtils.callFunctions();
    
    module.exports = userUtils;
    

    以上代码中,需要在func2和func1调用成功后调用func3。 所以这里我们在 chanks 中分离函数并从单个位置 userUtils.allFunctionCall() 调用它并在 for 循环中调用它,并使用 Promise.all() 处理它。通过这个,您可以轻松地调试您的代码,也易于其他开发人员理解。

    我希望它有所帮助,快乐编码:)

    【讨论】:

      猜你喜欢
      • 2022-08-05
      • 1970-01-01
      • 2017-12-08
      • 2019-09-03
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2013-05-26
      • 1970-01-01
      相关资源
      最近更新 更多