NodeJS-多次等待调用以顺序构建输出对象

时间:2019-10-16 00:40:53

标签: node.js asynchronous async-await export-to-csv

我有一个过程,其中用户上传CSV文件,然后使用CSV2JSON模块读取CSV文件。然后,我遍历CSV的各行,并查询多个Web服务调用以生成一个包含该Web服务调用结果的新CSV文件。

我在使用async / await方法构建输出时遇到问题,因为我需要等待服务调用完成以构建输出对象...

我得到的错误是:

  

等待仅在异步功能中有效

我将如何使用多次等待来获取输出?

const csv2json = require("csvtojson");
const json2csv = require("jsontocsv");
const path = require('path');
const axios = require("axios");

//---------------------------------------------------------------------------------------------
async function getCSVtoJSON(filePath, callback) {
    //set the file parth
    var csvFile = path.join(__dirname + '\\..\\' + filePath);

    try {
        await csv2json()
            .fromFile(csvFile)
            .then((jsonObj) => {
                callback(jsonObj);
            });
    } catch (e) {
        console.log(e);
    }
};

//---------------------------------------------------------------------------------------------
async function getWS(endpointURL, par1, par2, callback) {
    try {
        var getURL = 'http://blabla.com/' + endpointURL + '?par1=' + par1 + '&par2=' + par2;

        //Add the request info as config items
        await axios(getURL)
            .then((objReturn) => {
                callback(objReturn.data);
            });

    } catch (e) {
        console.log(e);
    }
}

//---------------------------------------------------------------------------------------------
async function processCSV(csvFilename) {
    let sourceCSV = [];
    let objList = [];
    let objOutput = [];
    let par1 = 0;
    let par2 = 0;


    //1st await is to get the csv data
    await getCSVtoJSON(csvFilename, function (csvJSON) {
        sourceCSV = csvJSON;
    });


    //now loop through each CSV line and build the output
    sourceCSV.forEach(function (csvLines) {

        //add the Source Data to the output
        let counter = 0;
        for (const key of Object.keys(csvLines)) {
            newKey = 'source_' + key;
            value = csvLines[key];
            //Start building the output object
            objList[newKey] = value;

            //set the par for the webservice calls
            if (counter == 1) { par1 = value; };
            if (counter == 2) { par2 = value; };
            counter++;
        }

        //Now link the data from web service 1
        await getWS('/call1/', par1, par2, function (returnData) {
            //process returnData and add the results to objList
        });

        //Now link the data from web service 2
        await getWS('/call2/', par1, par2, function (returnData2) {
            //process returnData2 and add the results to objList
        });

        //Now link the data from web service 3
        await getWS('/call3/', par1, par2, function (returnData3) {
            //process returnData3 and add the results to objList
        });

    });  //end loop csv lines

    //Now push the resultline to the main obj and continue with loop 
    objOutput.push(objList);

};

//Now write out the main obj to the result CSV

1 个答案:

答案 0 :(得分:2)

您还需要为嵌套方法加上async前缀。简化示例:

将不起作用:

async function doAThing() {
  const result = await promiseReturningCall();
  function inner() {
     const innerResult = await anotherPromiseReturningCall();
  }
}

将工作:

async function doAThing() {
  const result = await promiseReturningCall();
  async function inner() {
     const innerResult = await anotherPromiseReturningCall();
  }
}