首页 > 解决方案 > 获取 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: [] }

标签: javascript

解决方案


你的循环没有按照你的想法做。

当你这样做:

const apiCall = fetch('...').then('...')

将立即发出请求,并且apiCall 是由以下人员返回的 Promisefetch()

您可能想要的是apiCall变成一个函数并调用循环的每次迭代

const apiCall = () => fetch('...').then('...');

for (let index = 0; index < 10; index++) {
    apiCall();// call the function
}

推荐阅读