Home > Web Front-end > JS Tutorial > How to Effectively Control the Rate of API Requests Using Async/Await and setTimeout?

How to Effectively Control the Rate of API Requests Using Async/Await and setTimeout?

Susan Sarandon
Release: 2024-12-27 17:38:11
Original
552 people have browsed it

How to Effectively Control the Rate of API Requests Using Async/Await and setTimeout?

Combination of Async Function Await setTimeout

In this code snippet, the asyncGenerator function attempts to utilize the async-await features to process a list of files from the Google API. However, the while loop executes too quickly, resulting in excessive API requests per second. To address this, the developer attempts to introduce a sleep function, listFiles, to delay the API requests.

The sleep function is designed to delay the execution of the listFiles function by 3000 milliseconds. However, the code is not functioning as intended. The issue lies in the setTimeout function, which does not natively return a promise that can be awaited.

To resolve this issue, it's necessary to promisify the setTimeout function via the timeout helper function:

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
Copy after login

Additionally, the sleep function can be modified to use the timeout helper function:

async function sleep(fn, ...args) {
    await timeout(3000);
    return fn(...args);
}
Copy after login

Alternatively, to slow down the while loop without using a callback-based sleep function, the following approach can be used:

while (goOn) {
  // other code
  var [parents] = await Promise.all([
      listFiles(nextPageToken).then(requestParents),
      timeout(5000)
  ]);
  // other code
}
Copy after login

This approach ensures that the computation of parents takes at least 5 seconds, effectively slowing down the loop.

The above is the detailed content of How to Effectively Control the Rate of API Requests Using Async/Await and setTimeout?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template