【发布时间】:2021-07-20 01:36:23
【问题描述】:
我正在使用 axios 向 API 发出 get 请求,以获取我必须保存到文件中的数据。
我想在发送另一个请求之前等待文件完成下载。 对 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, element.url, 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, element.url, 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
【问题讨论】:
-
forEach没有阻塞。在上述情况下,您应该使用for循环。此答案中也概述了stackoverflow.com/a/46086037/5927442
标签: node.js async-await promise axios node-streams