在向前移动节点 Js axios 之前等待文件完成管道

问题描述

我正在使用 axios 向 API 发出获取请求,以获取我必须保存到文件中的数据。

我想在发送另一个请求之前等待文件完成下载。 对 async await 和 nodejs 还是新手。

jobOutputArr 包含一组 URL 和元素,我正在循环访问所有 URL 以获取要写入文件的数据。

function downloadFiles(filename,url,headers) {
    axios({
       url: url,method: "GET",headers: headers,responseType: 'stream'
   })
   .then(function (response){
        console.log('Connecting …')
        var path = Path.resolve(__dirname,filename)
        var writer = Fs.createWriteStream(path)
        response.data.pipe(writer)
        console.log('File Downloaded…'+filename)
   })
    
}

app.get('/downloadFiles',(req,res) => {

    var headers = {
        'Authorization': "Bearer " + accesstokenReceived,'Accept-Encoding': 'gzip'
    }

    //Downloading files

    let fileList = new Object();
    var filename

    fileList = {
        ExplanationOfBenefit : 0,Patient : 0,Coverage : 0
    }
    jobOutputArr.forEach( async element => {
        switch(element.type){
            case "ExplanationOfBenefit":
                filename = "ExplanationOfBenefit_"+fileList.ExplanationOfBenefit+".ndjson"
                fileList.ExplanationOfBenefit+=1
                console.log("Going in for "+filename)
                await downloadFiles(filename,element.url,headers)
                console.log("Coming out for "+filename)
                break;
            case "Patient":
                filename = "Patient_"+fileList.Patient+".ndjson"
                fileList.Patient+=1
                console.log("Going in for "+filename)
                await downloadFiles(filename,headers)
                console.log("Coming out for "+filename)
                break;
            case "Coverage":
                filename = "Coverage_"+fileList.Coverage+".ndjson"
                fileList.Coverage+=1
                console.log("Going in for "+filename)
                await downloadFiles(filename,headers)
                console.log("Coming out for "+filename)
                break;
        }
        
        
    })
    res.send("Done!")
})

我得到的输出

Going in for Patient_0.ndjson
Going in for Coverage_0.ndjson
Going in for ExplanationOfBenefit_0.ndjson
Coming out for ExplanationOfBenefit_0.ndjson
Coming out for ExplanationOfBenefit_0.ndjson
Coming out for ExplanationOfBenefit_0.ndjson
Connecting …
File Downloaded…Patient_0.ndjson
Connecting …
File Downloaded…ExplanationOfBenefit_0.ndjson
Connecting …
File Downloaded…Coverage_0.ndjson

我希望的输出

Going in for Patient_0.ndjson
Connecting …
File Downloaded…Patient_0.ndjson
Coming out for Patient_0.ndjson
Going in for Coverage_0.ndjson
Connecting …
File Downloaded…Coverage_0.ndjson
Coming out for Coverage_0.ndjson
Going in for ExplanationOfBenefit_0.ndjson
Connecting …
File Downloaded…ExplanationOfBenefit_0.ndjson
Coming out for ExplanationOfBenefit_0.ndjson

解决方法

尝试将 return 放在 axios 和 response.data 之前