简体   繁体   English

在循环内设置计时器以进行 graphql 查询

[英]set timer inside a loop for graphql query

The thing I'm doing here is fetching anime characters from anilist graphql api.我在这里做的是从anilist graphql api 获取动漫角色。 The reason I've added a loop is so I could fetch data from a certain character id to a limit.我添加循环的原因是我可以从某个字符 id 获取数据到一个限制。 For example 1-100.例如 1-100。 But I want to respect their API rate limits and so I'd like a way to limit my requests to 1 per second.但我想尊重他们的 API 速率限制,所以我想要一种将我的请求限制为每秒 1 次的方法。 Hence, I've used setTimeout , but I still got rate-limited from the API and using setInterval only keeps on looping it every 5 seconds.因此,我使用了setTimeout ,但我仍然受到 API 的速率限制,并且使用setInterval只会每 5 秒循环一次。 Like the same data gets fetched every 5 seconds.就像每 5 秒获取相同的数据一样。 Is there any way I can make it as I've mentioned?正如我所提到的,有什么办法可以做到吗?

My code:我的代码:

const fs = require("fs");
const number = 3;
const axios = require("axios");

async function fetchData() {
  for (let i = 1; i <= number; i++) {
    const query = axios
      .post(
        "https://graphql.anilist.co",
        {
          query: `query character(
                    $id: Int
                    $page: Int
                    $sort: [MediaSort]
                    $onList: Boolean
                    $withRoles: Boolean = false
                  ) {
                    Character(id: $id) {
                      id
                      name {
                        first
                        middle
                        last
                        full
                        native
                        userPreferred
                        alternative
                        alternativeSpoiler
                      }
                      image {
                        large
                      }
                      favourites
                      isFavourite
                      isFavouriteBlocked
                      description
                      age
                      gender
                      bloodType
                      dateOfBirth {
                        year
                        month
                        day
                      }
                      media(page: $page, sort: $sort, onList: $onList) @include(if: $withRoles) {
                        pageInfo {
                          total
                          perPage
                          currentPage
                          lastPage
                          hasNextPage
                        }
                        edges {
                          id
                          characterRole
                          voiceActorRoles(sort: [RELEVANCE, ID]) {
                            roleNotes
                            voiceActor {
                              id
                              name {
                                userPreferred
                              }
                              image {
                                large
                              }
                              language: languageV2
                            }
                          }
                          node {
                            id
                            type
                            isAdult
                            bannerImage
                            title {
                              userPreferred
                            }
                            coverImage {
                              large
                            }
                            startDate {
                              year
                            }
                            mediaListEntry {
                              id
                              status
                            }
                          }
                        }
                      }
                    }
                  }`,
          variables: {
            id: i,
            withRoles: false,
          },
        },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      )
      .then((response) => {
        // console.log(response.data.data.Character)
        const jsonContent =
          JSON.stringify(response.data.data.Character, null, 4) + ", ";

        fs.appendFile("./chars.json", jsonContent, function (err) {
          if (err) {
            return console.log(err);
          }

          console.log("The file was saved!");
        });
      })
      .catch((error) => console.log(`Code: ${error}`, error));
  }
}

fetchData();

Something like that will work for you (Asuming all the rest was ok):类似的东西对你有用(假设所有其他的都好):

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function fetchData() {
  for (let i = 1; i <= number; i++) {
    const query = axios.post(
      "https://graphql.anilist.co",
      {
        query: someQuery, // TODO: Set your query here
        variables: {
          id: i,
          withRoles: false
        }
      },
      {
        headers: {
          "Content-Type": "application/json"
        }
      }
    );

    let response;
    try {
      response = await query;
    } catch (e) {
      console.log(`Code: ${e}`, e);
      return; // or handle in some different way
    }

    const jsonContent =
      JSON.stringify(response.data.data.Character, null, 4) + ", ";

    fs.appendFile("./chars.json", jsonContent, function (err) {
      if (err) {
        return console.log(err);
      }
      console.log("The file was saved!");
    });

    await delay(5000); // TODO: Change to whatever you need
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM