Ryan H
Ryan H

Reputation: 2945

Express JS handle multiple requests and return responses to browser that made request

I've created a little Express JS api which takes in data about a user, in this case, an application containing many form fields. The idea behind my Express JS endpoint is to simply handle the requests to and from a server, and then report back to the browser that made the request (the user), my current set up is:

let applications = {}

app.post('/api/submit/:id', (req, res) => {

  try {

    submitApplication(req.body, req.params.id)

    res.status(200).send({
      code: 200,
      success: true
    })

  } catch (error) {

    // handle error

  }

})


function submitApplication (body, id) {

  applications[id] = body != null ? body : {}

  const application = applications[id]

  application.Result = 'Processing'

  axios.post('https://example.com/api', JSON.stringify(applications[id]), {
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {

          application.Result = response.data.Result

        })
        .catch(error => {

          // error

        });
}

In the code above, there could be 10 different browsers, each submitting data to the Express JS end point, :id is a unique generated number that I generate on the client side in the browser so that the individual axios requests can update the relevant application by it's ID.

I'm trying to figure out whether Let's say... John submits an application, followed by Jane, whether the submitApplication function will run in parallel, or wait until the first has finished, it looks like from my observations that it's running in parallel and isn't waiting until the first finishes, which is what I need, but I'm not sure.

The api referenced in Axios, could take up-to 3 minutes for it to return a response.

Upvotes: 0

Views: 1750

Answers (1)

O. Jones
O. Jones

Reputation: 108651

Yes, things run "in parallel" on nodejs. Your code handles context correctly so multiple axios operations do not confuse data with each other.

If you're not sure about this read about Promises. They're how .then().catch() are implemented.

Notice that in this code of yours:

submitApplication(req.body, req.params.id)
res.status(200).send({code: 200,success: true})

The second line runs immediately, not when axios successfully completes. If you want to wait, you'll have to run the second line from within a callback or Promise.then() function.

Also note: if you generate id numbers randomly in your client, you would be wise to select them from a very large range of numbers to reduce the probability of collisions.

Upvotes: 1

Related Questions