Combining Async Functions, Await, and setTimeout
Utilizing the latest JavaScript async features, this guide provides a solution to a common performance issue: sending excessive requests to Google APIs in a short timeframe. The goal is to introduce a sleep function to delay requests and enhance script performance.
Original Code:
This initial code employs the async/await pattern efficiently:
async function asyncGenerator() { while (goOn) { var fileList = await listFiles(nextPageToken); var parents = await requestParents(fileList); } }
Problem:
The code executes the while loop too rapidly, resulting in a deluge of requests to the Google API.
Attempted Solution:
To address this, a sleep function was created:
async function sleep(fn, par) { return await setTimeout(async function() { await fn(par); }, 3000, fn, par); }
However, this function fails to return the request response properly.
Correct Implementation:
The issue with the sleep function lies in the lack of a promise returned by setTimeout. To resolve this, a promisified version can be created:
function timeout(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function sleep(fn, ...args) { await timeout(3000); return fn(...args); }
Optimized Loop:
To slow down the loop execution, a sleep function that pauses the entire computation is not optimal. A better approach is to use a Promise.all construct that includes the sleep function:
while (goOn) { var [parents] = await Promise.all([ listFiles(nextPageToken).then(requestParents), timeout(5000) ]); }
This modification ensures that the computation of parents takes a minimum of 5 seconds, effectively slowing down the loop and preventing excessive API requests.
The above is the detailed content of How Can I Prevent Excessive API Requests When Using Async/Await in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!