How can I force sequential execution on 2 simultaneous requests?

Discussion in 'JavaScript' started by SoftLink, May 30, 2024.

  1. #1
    I've got an input form with 2 inputs.
    Each input value (not the whole form) is sent to the server immediately after it's set.
    I can pretty much make both inputs submit simultaneously.
    I fill in the text box and without leaving (blur) I click a checkbox.

    The server gets the second request before it can process the first.
    The second needs an ID that is generated during the processing of the first.
    The second is so quick that it precedes the generation of the ID so it thinks it's the first and generates another ID.

    Sessions in this case are not possible. The entire client side is javascript.
    There are no session variables. I do create a session.
    The app generates a unique 'session' ID when it receives the first *page* (not form) request from a given visitor and saves it to a db record. It sends the session ID in the response to the client. All subsequent *form* requests from that visitor include the session ID.

    When the server gets the first *form* request from that visitor it generates another (not the session) ID which each subsequent form request from that visitor needs.

    The app fills the session record with the ID as soon as it gets the first form request.
    It's TOO LATE! The server gets the second request before the ID is generated.
    The second doesn't see the new ID, thinks it's the first and generates another ID.

    I can force a delay if there's no ID yet but that's awful sloppy, not efficient.

    How can I guarantee that the second form request will see the new ID that the first generated?
     
    SoftLink, May 30, 2024 IP
  2. GreenHost.Cloud

    GreenHost.Cloud Member

    Messages:
    204
    Likes Received:
    15
    Best Answers:
    3
    Trophy Points:
    33
    #2
    To make sure things happen in the right order, you could set up a system in JavaScript where the second input is only sent once the first input's ID is ready. This ensures that the server gets the information it needs in the right order. Another option is to use async requests and manage how the two inputs work together. It's also important to make sure the server code knows how to handle IDs in order to prevent any mix-ups.
     
    GreenHost.Cloud, Jun 8, 2024 IP
    SoftLink likes this.
  3. sarahk

    sarahk iTamer Staff

    Messages:
    28,572
    Likes Received:
    4,474
    Best Answers:
    123
    Trophy Points:
    665
    #3
    Look up Promises.
     
    sarahk, Jun 9, 2024 IP
  4. SoftLink

    SoftLink Active Member

    Messages:
    120
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #4
    GreenHost: Thanks for your response.
    The form actually has x number of inputs depending on the usage, usually up to 25.
    I don't care which is 'first', I only care that the 'second' uses the ID generated by the first.
    I can't slow the user's input values at all. He needs to be able to set values as quickly as possible.
    I don't see how I could do this without async. I don't want to delay the second until I get the first.
    I suppose I could create some type of que on the client but I don't like that idea.
    So far I'm delaying on the server 1 whole minute (that's what it took) which *seems* to have solved the problem.
    I don't like it and I'm not convinced it's a guaranteed solution.
    I'm guessing a cue is the only way to go;
    hold the subsequent values in que until the client has the ID.
    I didn't really want to send the ID to the client at all.

    sarahk: Thanks for your response.
    How did you intend for me to use promises? Were you thinking of creating a que on the client? or something else?
     
    SoftLink, Jun 10, 2024 IP
  5. sarahk

    sarahk iTamer Staff

    Messages:
    28,572
    Likes Received:
    4,474
    Best Answers:
    123
    Trophy Points:
    665
    #5
    Promises let you chain your requests but I'm wondering if the whole work flow needs a peer review.
     
    sarahk, Jun 10, 2024 IP
  6. DuneDreamer

    DuneDreamer Well-Known Member

    Messages:
    364
    Likes Received:
    213
    Best Answers:
    0
    Trophy Points:
    135
    #6
    I think you should use the chaining of promises: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#chaining_promises
    You should also care which input is first. If the second input uses the ID generated by the first, you should disable it until the request from the first input does it's job and returns the ID.
    I also think that delaying the server is the wrong way to do it. If your async request does its job and returns data in 20 seconds, why should the user wait for 1 minute? I'll be gone from your form by then if it doesn't concern my life.
     
    DuneDreamer, Jun 17, 2024 IP
  7. hooman64

    hooman64 Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #7
    To force sequential execution on two simultaneous requests, you need to control the order in which the requests are made and ensure that the second request only starts after the first one has completed. This can be done using different approaches depending on the programming language and environment you are working in. Here are some common methods for popular languages:JavaScript (Using Promises)If you are working with JavaScript, especially in a Node.js environment or browser, you can use Promises to ensure sequential execution:function request1() {
    return new Promise((resolve, reject) => {
    // Simulate an async request
    setTimeout(() => {
    console.log('Request 1 completed');
    resolve('Data from request 1');
    }, 1000);
    });
    }

    function request2(data) {
    return new Promise((resolve, reject) => {
    // Simulate an async request
    setTimeout(() => {
    console.log('Request 2 completed with data:', data);
    resolve('Data from request 2');
    }, 1000);
    });
    }

    async function makeRequestsSequentially() {
    try {
    const data1 = await request1();
    const data2 = await request2(data1);
    console.log('All requests completed');
    } catch (error) {
    console.error('Error:', error);
    }
    }

    makeRequestsSequentially();Python (Using asyncio)In Python, you can use the asyncio library to handle asynchronous tasks sequentially:import asyncio

    async def request1():
    await asyncio.sleep(1) # Simulate an async request
    print('Request 1 completed')
    return 'Data from request 1'

    async def request2(data):
    await asyncio.sleep(1) # Simulate an async request
    print('Request 2 completed with data:', data)
    return 'Data from request 2'

    async def main():
    data1 = await request1()
    data2 = await request2(data1)
    print('All requests completed')

    # Run the main function
    asyncio.run(main())Java (Using CompletableFuture)In Java, you can use CompletableFuture for handling asynchronous tasks sequentially:import java.util.concurrent.CompletableFuture;

    public class SequentialRequests {

    public static CompletableFuture<String> request1() {
    return CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(1000); // Simulate an async request
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("Request 1 completed");
    return "Data from request 1";
    });
    }

    public static CompletableFuture<String> request2(String data) {
    return CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(1000); // Simulate an async request
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("Request 2 completed with data: " + data);
    return "Data from request 2";
    });
    }

    public static void main(String[] args) {
    request1().thenCompose(data1 -> request2(data1))
    .thenAccept(data2 -> System.out.println("All requests completed"))
    .join();
    }
    }Sequential Execution SummaryJavaScript: Use async/await with Promises.Python: Use asyncio with await.Java: Use CompletableFuture with thenCompose.These methods ensure that the second request is made only after the first one has been completed, maintaining sequential execution.
     
    hooman64, Jul 6, 2024 IP