您遇到的第一个问题是您每次都创建流。这将在每次解决承诺时覆盖内容。删除此行。
const writeStream = fs.createWriteStream('wip.json');
你会有这样的东西。
const axios = require('axios');
const fs = require('fs');
const config = require('./config/secret.json');
const writeStream = fs.createWriteStream('wip.json');
app.get('/json', (req,res) => {
const linkArr = ['https://apirequest1.com','https://apirequest2.com','https://apirequest3.com','https://apirequest4.com', '...'];
const wipArr = [];
for(let getAPI of linkArr){
axios({
method: 'get',
url: getAPI,
auth: {username: config.username, password: config.secret}
})
.then(function (response){
//const writeStream = fs.createWriteStream('wip.json'); // remove this line because it will overwrite the file for each response.
writeStream.write(JSON.stringify(response.data));
})
.catch(function (error){
console.log(error);
})
}
res.send('successfully saved all response');
})
;
编辑:要等待所有请求,您可以尝试这样的事情。
app.get('/json', async (req, res) => {
let resp = null;
const writeStream = fs.createWriteStream('wip.json');
const linkArr = ['https://apirequest1.com', 'https://apirequest2.com', 'https://apirequest3.com', 'https://apirequest4.com', '...'];
const promises = [];
for (let getAPI of linkArr) {
promises.push(makeCall(getAPI));
resp = await Promise.all(promises); // resp is array of responses
// for (let i = 0; i < resp.length; i++) {
// writeStream.write(JSON.stringify(resp[i], null, 4)); // to //format the json string
// }
}
for (let i = 0; i < resp.length; i++) {
writeStream.write(JSON.stringify(resp[i], null, 4)); // to format the json string
}
res.send('successfully saved all response');
});
function makeCall(getAPI) {
axios({
method: 'get',
url: getAPI,
auth: { username: config.username, password: config.secret }
})
.then(function(response) {
return response.data;
});
}
我还没有测试过它,但类似的东西。这将运行所有请求。
要格式化 JSON 字符串,您可以使用。
JSON.stringify(resp[i], null, 4).
看看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
编辑:问题是writeStream.write(JSON.stringify(resp[i], null, 4));
在循环内。把它移到了外面。
添加代码而无需测试。这应该适合你。
app.get('/json', async(req, res) => {
const writeStream = fs.createWriteStream('wip.json');
const linkArr = ['https://apirequest1.com', 'https://apirequest2.com', 'https://apirequest3.com', 'https://apirequest4.com', '...'];
const promises = [];
for (let getAPI of linkArr) {
promises.push(makeCall(getAPI));
}
const resp = await Promise.all(promises); // resp is array of responses
for (let i = 0; i < resp.length; i++) {
writeStream.write(JSON.stringify(resp[i], null, 4)); // to format the json string
}
res.send('successfully saved all response');
});
function makeCall(getAPI) {
return axios({
method: 'get',
url: getAPI,
auth: { username: config.username, password: config.secret }
})
}