node.js中的异步函数问题

时间:2018-02-19 02:06:36

标签: node.js

我对节点非常陌生,我试图从API中提取ID列表,为每个ID迭代该列表以保存输出,并最终重命名生成的每个文件。下面的代码是我最接近的代码,虽然它有时会工作,但它经常会失败,因为我相信一个函数不等待另一个函数完成(例如在写入之前尝试读取),但是我和#39;我确定我还有其他问题。

const apiKey = inputData.apiKey

var https = require('https');
var sync = require('sync');
var fs = require('fs');

var JSONfileloc = "./pdfs/file.json"
var queryurl = 'https://intakeq.com/api/v1/intakes/summary?startDate=2018-01-01'
var authHeaders = { 'X-Auth-Key': apiKey }
var queryOpts = { method: 'GET', headers: authHeaders}


function handleFile (error, file) 
{
   if (error) return console.error('Ran into a problem here', error)
 }


fetch(queryurl, queryOpts)
.then
(function findAPI(res, err)
    {
    if( err ) 
        {       console.log('I cant find the API '+err)         }
        return res.json()
        {console.log('found the API!')}
    }
)

.then (function itID(res, err)
    { 
    if( err ) 
        {       console.log('I cant iterate the API '+err)      }
    for(var i = 0; i < res.length; i++) 
        {
           var intakeID=res[i].Id;
           var APIoptions={   host:"intakeq.com",   path:"/api/v1/intakes/"+ intakeID,   headers: authHeaders };
           var PDFoptions={   host:"intakeq.com",   path:"/api/v1/intakes/"+ intakeID+'/pdf',   headers: authHeaders };
    console.log('Working on ID:'+intakeID)
    var JSONrequest = https.get(APIoptions, writeJSON)

    }})


//READ JSON FUNCTION

function readJSON (err, data) 

{
        if (err) throw err;
        if(data.indexOf('New Patient Forms') >= 0)

        var contents = fs.readFileSync(JSONfileloc, handleFile);
        var jsonContent = JSON.parse(contents)

        //pull PT Name
        pName = (jsonContent.ClientName);
        console.log('The Patient Name Is ' + jsonContent.ClientName)

        //pull PT DOB
        pDob = (jsonContent.Questions[3].Answer)
        console.log('Patient DOB Is ' + jsonContent.Questions[3].Answer)

        //pull Form Type
        pForm = (jsonContent.QuestionnaireName)
        console.log('The Form Submitted is ' + jsonContent.QuestionnaireName)

        //rename and move JSON
        fs.rename("./pdfs/file.json", './JSONLogs/'+pName+' '+pForm+' '+Date.now()+'.json', function(err) {
        if ( err ) console.log('Problem renaming! ' + err)
        else console.log('Copying & Renaming JSON File!');
        })

        };

//WRITE JSON FUNCTION
function writeJSON(response, err)
    {
    var JSONfile = fs.createWriteStream(JSONfileloc, handleFile);
    if (err) throw err;
    response.pipe(JSONfile);
    console.log('JSON Created')
    fs.readFile(JSONfileloc, readJSON)
    }

我所做的研究让我相信async.forEach可能是正确的方法,但我一直很难让它正常工作。在此先感谢,任何建议都非常感谢。

1 个答案:

答案 0 :(得分:0)

return $http.get(apiTarget, { responseType: 'blob' });

更新以转换const apiKey = inputData.apiKey var https = require('https'); var sync = require('sync'); var fs = require('fs'); var JSONfileloc = "./pdfs/file.json" var queryurl = 'https://intakeq.com/api/v1/intakes/summary?startDate=2018-01-01' var authHeaders = { 'X-Auth-Key': apiKey } var queryOpts = { method: 'GET', headers: authHeaders } function handleFile(error, file) { if (error) return console.error('Ran into a problem here', error) } fetch(queryurl, queryOpts) .then(function findAPI(res) { return res.json(); }) .then(function itID(res) { const JSONRequests = []; for (var i = 0; i < res.length; i++) { var intakeID = res[i].Id; var APIoptions = { host: "intakeq.com", path: "/api/v1/intakes/" + intakeID, headers: authHeaders }; var PDFoptions = { host: "intakeq.com", path: "/api/v1/intakes/" + intakeID + '/pdf', headers: authHeaders }; // https.get has response as a stream and not a promise // This `httpsGet` function converts it to a promise JSONRequests.push(httpsGet(APIoptions, i)); } return Promise.all(JSONRequests); }) function httpsGet(options, filename) { return new Promise((resolve, reject) => { https.get(options, (response) => { // The WriteJSON function, just for brewity // Otherwise pass resolve to the seperate writeJSON and call it in there var JSONfile = fs.createWriteStream(filename + ".json"); response.pipe(JSONfile); JSONfile.on('close', () => { readJSON(filename + ".json").then(() => { resolve(); }) }) }) }) } //READ JSON FUNCTION function readJSON(filename) { // if (err) throw err; var contents = fs.readFileSync(filename, 'utf-8'); // removed handleFile as readFileSync does not allow callbacks, added format var jsonContent = JSON.parse(contents) // Make your conditional checks here with the jsonContents //pull PT Name pName = (jsonContent.ClientName); console.log('The Patient Name Is ' + jsonContent.ClientName) //pull PT DOB pDob = (jsonContent.Questions[3].Answer) console.log('Patient DOB Is ' + jsonContent.Questions[3].Answer) //pull Form Type pForm = (jsonContent.QuestionnaireName) console.log('The Form Submitted is ' + jsonContent.QuestionnaireName) //rename and move JSON return new Promise((resolve, reject) => { fs.rename("./pdfs/file.json", './JSONLogs/' + pName + ' ' + pForm + ' ' + Date.now() + '.json', function (err) { if (err) { console.log('Problem renaming! ' + err); reject(err); } else { console.log('Copying & Renaming JSON File!'); resolve(); } }) }) }; 响应流以返回可以更好地处理的Promise。