javascript - 获取 api 10 次
问题描述
我尝试通过将 fetch 调用包装在 for 循环中来调用端点 10 次。但结果显示一个 api 调用。所以我想知道这是不是错误的做法?
const fetch = require("node-fetch");
const apiCall = fetch('url')
.then(response => response.json())
.then(jsonResponse => {
console.log(jsonResponse)
})
for (let index = 0; index < 10; index++) {
apiCall;
}
结果:
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
预期成绩:
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
{ totalRecords: 0, totalPages: 0, page: 0, items: [] }
解决方案
你的循环没有按照你的想法做。
当你这样做:
const apiCall = fetch('...').then('...')
将立即发出请求,并且apiCall
是由以下人员返回的 Promisefetch()
您可能想要的是apiCall
变成一个函数并调用循环的每次迭代
const apiCall = () => fetch('...').then('...');
for (let index = 0; index < 10; index++) {
apiCall();// call the function
}
推荐阅读
- python - sparse_categorical_crossentropy() 缺少 2 个必需的位置参数:“y_true”和“y_pred”
- c# - VS 代码调试器在带有 M1 芯片的 Mac 上不起作用
- microsoft-graph-api - Microsoft Graph API 是否支持 Outlook 消息订阅/通知的增量链接?
- c++ - 错误:指定的可执行文件不是此操作系统平台的有效应用程序。行:1 字符:1
- c++ - 按 control+Z 后有没有办法继续输入?
- machine-learning - 在 LSTM 中,什么情况下一个内存块应该有多个内存单元?
- django - 当我尝试在 django 中更新多个图像时出现错误
- mysql - 尝试访问实时数据库中的某些表时出现错误 1146
- reactjs - react-query 在 nextjs 中重新获取页面更改的数据
- python - 我的 cookie-navbar 组合不起作用,即使我没有收到错误