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)); }
Additionally, the sleep function can be modified to use the timeout helper function:
async function sleep(fn, ...args) { await timeout(3000); return fn(...args); }
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 }
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!