我有一个在 Azure 函数中运行的 API,需要在循环中运行多次,以便我可以获得所有结果。
运行时的第一个API。它返回标题中带有 locator 参数的结果。使用 locator 参数,我们需要在循环内调用 api 来获取所有结果。 locator 当 API 被调用时,参数将始终具有新值。
每次我想将响应写入新文件时。如何使用不同的 locator 参数调用相同的 api,直到 locator 值变为 null
const getjobresult = async(t) => {
const requestOptions = {
method: "GET",
headers: {
"Content-Type": 'application/json',
"Accept": "text/csv",
"Authorization": "Bearer " + t
},
redirect: "follow"
};
// This below api is called for first time where it returns 500000 records (which i am writing in a file ) and a parameter locator which contains a value through which we will get another set of record
const resp = await fetch("https://someapi.test.com/services/data/v59.0/jobs/query/750Pw000005PqqBIAS/results?maxRecords=500000", requestOptions)
const json = await resp.text();
const fields = ['Id']
let aa = resp.headers.get('locator')
const rows = json.split((/\r?\n|\r/)).slice(1);
let lsttis = []
rows.forEach(res => {
let tis = {
'tablename': 'TestTable'
};
tis.AccessLevel = 'Read';
tis.ParentId = res.replace(/['"]+/g, '')
tis.RowCause = 'Manual'
tis.UserOrGroupId = '11111111'
lsttis.push(tis)
})
if (lsttis.length > 0) {
await creatcsvfile(lsttis)
}
// In this below code i am trying to refire the api using locator parameter inside a while loop.Everytime when api gets hit inside while loop, it returns a new locator value. This while loop should run till resp1.headers.get('locator') becomes null and everytime the response should be written in
// new file.
var i = 0;
while (true) {
i++;
const resp1 = await fetch("https://someapi.com/services/data/v59.0/jobs/query/750Pw000005PqqBIAS/results?locator=" + aa + "&maxRecords=500000", requestOptions)
const json1 = await resp1.text();
if (resp1.headers.get('locator') === undefined) {
break;
}
const rows1 = json1.split((/\r?\n|\r/)).slice(1);
rows1.forEach(res => {
let tis = {
'tablename': 'TestTable'
};
tis.AccessLevel = 'Read';
tis.ParentId = res.replace(/['"]+/g, '')
tis.RowCause = 'Manual'
tis.UserOrGroupId = '11111111'
lsttis.push(tis)
})
// in this i am sending the i for creating new file for every response.
if (lsttis.length > 0) {
await creatcsvfile(lsttis, i)
}
}
}
const creatcsvfile = async(data, t) => {
const fields = ['AccessLevel', 'ParentId', 'RowCause', 'UserOrGroupId']
let csv = await json2csv.parse(data, {
fields
});
//console.log(csv)
fs.writeFileSync('./test' + t + '.csv', csv)
}
因此,假设您的代码有效并且您只是在谈论优化,我可以建议一些提示:
我首先想到的是:不要在 JavaScript 中使用 var。提升问题可能是一个问题(不是你的情况),但我真的建议避免它。
第二:创建函数来隔离职责,创建一个类似于您创建的 creatcsvfile 的函数。创建一个只是为了获取和解析,另一个只是为了在行内执行 for 循环。这将创建一个更清晰、可读的代码。
第三:你可以删除第一个 api 调用和循环,只需要调整 while 循环内的内容(这样你就可以只调用所有这些),例如:
let aa = 0
因此,当您点击 API 时,它会发送定位器,但它会知道这是第一次调用。如果您的 api 不支持此功能,您可以将“aa”创建为未定义,并仅在其初始化时才传递给 fetch。像这样使用 JS 模板字符串:
let aa;
const resp1 = await fetch(`https://someapi.com/services/data/v59.0/jobs/query/750Pw000005PqqBIAS/results?${aa? "locator="+aa:""}&maxRecords=500000`, requestOptions)