Home > Web Front-end > JS Tutorial > How Can I Prevent Excessive API Requests When Using Async/Await in JavaScript?

How Can I Prevent Excessive API Requests When Using Async/Await in JavaScript?

Susan Sarandon
Release: 2024-12-15 12:34:11
Original
371 people have browsed it

How Can I Prevent Excessive API Requests When Using Async/Await in JavaScript?

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);
    }
}
Copy after login

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);
}
Copy after login

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);
}
Copy after login

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)
    ]);
}
Copy after login

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!

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