Home Web Front-end JS Tutorial How to efficiently handle multiple asynchronous requests in Tampermonkey and determine the continuation or termination of control requests based on conditions?

How to efficiently handle multiple asynchronous requests in Tampermonkey and determine the continuation or termination of control requests based on conditions?

Apr 04, 2025 pm 12:39 PM
ai Concurrent requests

How to efficiently handle multiple asynchronous requests in Tampermonkey and determine the continuation or termination of control requests based on conditions?

This article discusses efficiently handling multiple asynchronous requests in Tampermonkey scripts and determines the continuation or termination of control requests based on conditions. This is very practical in scenarios where data needs to be fetched from multiple URLs and make decisions based on the data.

Problem Description: The Tampermonkey script needs to obtain data from multiple URLs and make conditional judgments based on these data. If a specific condition is met, the subsequent request is stopped; otherwise, the next request continues.

Challenge: Using the loop method of gm_xmlhttpRequest directly will execute all requests in sequence and cannot be stopped immediately after the conditions are met.

Solution: This article provides two solutions, namely sequential requests and concurrent requests, both of which can effectively terminate subsequent requests after the conditions are met.

Scheme 1: Sequential requests (using Promise and recursion)

This plan initiates requests in turn and makes conditional judgments after each request is completed. If the condition is satisfied, it terminates recursively; otherwise, continue to the next request.

 function promise1() { return new Promise(resolve => setTimeout(() => resolve({data: '123'}), 2000)); }
function promise2() { return new Promise(resolve => setTimeout(() => resolve({data: '#234'}), 2000)); }
function promise3() { return new Promise(resolve => setTimeout(() => resolve({data: '1'}), 2000)); }

function mainRequest(promises) {
  return new Promise(resolve => {
    let i = 0;
    function nextRequest() {
      if (i === promises.length) { resolve('all do not meet the criteria'); return; }
      const request = promises[i]();
      i ;
      request.then(result => {
        if (result.data.indexOf('#') > -1) { resolve(result.data); }
        else { nextRequest(); }
      }).catch(() => nextRequest()); // Handle error}
    nextRequest();
  });
}

mainRequest([promise3, promise2, promise1]).then(result => console.log('result', result));
Copy after login

Solution 2: Concurrent requests (using Promise.all and conditional judgment)

This scheme initiates all requests at the same time, and uses Promise.all to wait for all requests to complete. Then, the traversal result is verified for conditional judgment, and then the first result that meets the condition is found and subsequent processing is stopped.

 function Promise1() { return new Promise(resolve => setTimeout(() => resolve({data: '#123'}), Math.random() * 1000)); }
function Promise2() { return new Promise(resolve => setTimeout(() => resolve({data: '#234'}), Math.random() * 1000)); }
function Promise3() { return new Promise(resolve => setTimeout(() => resolve({data: '#1'}), Math.random() * 1000)); }

function mainRequest(promises) {
  return Promise.all(promises.map(p => p())).then(results => {
    for (let i = 0; i  -1) { return { successIndex: i, data: results[i].data }; }
    }
    return 'No request matching the criteria was found';
  });
}

mainRequest([Promise3, Promise2, Promise1]).then(result => console.log('result', result));
Copy after login

Summary: Both solutions achieve the goal of stopping subsequent requests after the conditions are met. Which solution to choose depends on the specific requirements: sequential requests save resources, concurrent requests are faster but consume more resources. It should be noted that gm_xmlhttpRequest itself does not provide the function of canceling the request, so in the concurrency scheme, we achieve the effect of "stop" by ignoring the subsequent results after finding the result that meets the condition. In actual applications, adjustments need to be made according to specific APIs and conditions.

The above is the detailed content of How to efficiently handle multiple asynchronous requests in Tampermonkey and determine the continuation or termination of control requests based on conditions?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the reason why PS keeps showing loading? What is the reason why PS keeps showing loading? Apr 06, 2025 pm 06:39 PM

PS "Loading" problems are caused by resource access or processing problems: hard disk reading speed is slow or bad: Use CrystalDiskInfo to check the hard disk health and replace the problematic hard disk. Insufficient memory: Upgrade memory to meet PS's needs for high-resolution images and complex layer processing. Graphics card drivers are outdated or corrupted: Update the drivers to optimize communication between the PS and the graphics card. File paths are too long or file names have special characters: use short paths and avoid special characters. PS's own problem: Reinstall or repair the PS installer.

How to solve the problem of loading when PS is started? How to solve the problem of loading when PS is started? Apr 06, 2025 pm 06:36 PM

A PS stuck on "Loading" when booting can be caused by various reasons: Disable corrupt or conflicting plugins. Delete or rename a corrupted configuration file. Close unnecessary programs or upgrade memory to avoid insufficient memory. Upgrade to a solid-state drive to speed up hard drive reading. Reinstalling PS to repair corrupt system files or installation package issues. View error information during the startup process of error log analysis.

How to use PS feathering to create transparent effects? How to use PS feathering to create transparent effects? Apr 06, 2025 pm 07:03 PM

Transparent effect production method: Use selection tool and feathering to cooperate: select transparent areas and feathering to soften edges; change the layer blending mode and opacity to control transparency. Use masks and feathers: select and feather areas; add layer masks, and grayscale gradient control transparency.

How is the compatibility of Bootstrap image centering How is the compatibility of Bootstrap image centering Apr 07, 2025 am 07:51 AM

Bootstrap image centering faces compatibility issues. The solution is as follows: Use mx-auto to center the image horizontally for display: block. Vertical centering Use Flexbox or Grid layouts to ensure that the parent element is vertically centered to align the child elements. For IE browser compatibility, use tools such as Autoprefixer to automatically add browser prefixes. Optimize image size, format and loading order to improve page performance.

What should I do if the PS card is in the loading interface? What should I do if the PS card is in the loading interface? Apr 06, 2025 pm 06:54 PM

The loading interface of PS card may be caused by the software itself (file corruption or plug-in conflict), system environment (due driver or system files corruption), or hardware (hard disk corruption or memory stick failure). First check whether the computer resources are sufficient, close the background program and release memory and CPU resources. Fix PS installation or check for compatibility issues for plug-ins. Update or fallback to the PS version. Check the graphics card driver and update it, and run the system file check. If you troubleshoot the above problems, you can try hard disk detection and memory testing.

How to change the size of a Bootstrap list? How to change the size of a Bootstrap list? Apr 07, 2025 am 10:45 AM

The size of a Bootstrap list depends on the size of the container that contains the list, not the list itself. Using Bootstrap's grid system or Flexbox can control the size of the container, thereby indirectly resizing the list items.

How to add icons to Bootstrap list? How to add icons to Bootstrap list? Apr 07, 2025 am 10:42 AM

How to add icons to the Bootstrap list: directly stuff the icon into the list item <li>, using the class name provided by the icon library (such as Font Awesome). Use the Bootstrap class to align icons and text (for example, d-flex, justify-content-between, align-items-center). Use the Bootstrap tag component (badge) to display numbers or status. Adjust the icon position (flex-direction: row-reverse;), control the style (CSS style). Common error: The icon does not display (not

How to implement nesting of Bootstrap lists? How to implement nesting of Bootstrap lists? Apr 07, 2025 am 10:27 AM

Nested lists in Bootstrap require the use of Bootstrap's grid system to control the style. First, use the outer layer <ul> and <li> to create a list, then wrap the inner layer list in <div class="row> and add <div class="col-md-6"> to the inner layer list to specify that the inner layer list occupies half the width of a row. In this way, the inner list can have the right one

See all articles