Multiple-sequential-execution- axios-request

Patient Tools

Read, save, and share this guide

Use these quick tools to make this medical article easier to read, print, save, or share with a family member.

Medical guide PHP, JS, CSS, Python, and Machine Learning Technology Feb 8, 2026 21 reads
Related reading

Patient Mode

Understand this article easily

Switch between simple English and easy Bangla patient notes. This is for education and does not replace a doctor consultation.

JavaScript is single threaded, that means only one statement is executed at a time. As the JS engine processes our script line by line, it uses this single Call-Stack to keep track of codes that are supposed to run in their respective order. Like what...

For severe symptoms, danger signs, pregnancy, child illness, or sudden worsening, seek urgent medical care.

বাংলা রোগী নোট এখনো যোগ করা হয়নি। পোস্ট এডিটরে “RX Bangla Patient Mode” বক্স থেকে সহজ বাংলা সারাংশ যোগ করুন।

এই তথ্য শিক্ষা ও সচেতনতার জন্য। এটি ডাক্তারি পরীক্ষা, রোগ নির্ণয় বা প্রেসক্রিপশনের বিকল্প নয়।

Article Summary

JavaScript is single threaded, that means only one statement is executed at a time. As the JS engine processes our script line by line, it uses this single Call-Stack to keep track of codes that are supposed to run in their respective order. Like what a stack does, a data structure which records lines of executable instructions and executes them in LIFO manner. So say...

Educational health guideWritten for patient understanding and clinical awareness.
Reviewed content workflowUse writer and reviewer profiles for stronger trust.
Emergency safety firstUrgent warning signs are highlighted below.

Seek urgent medical care if you notice

These warning signs are general safety guidance. Local emergency numbers and clinical judgment should always come first.

  • Severe symptoms, breathing difficulty, fainting, confusion, or rapidly worsening illness.
  • New weakness, severe pain, high fever, or symptoms after a serious injury.
  • Any symptom that feels urgent, unusual, or unsafe for the patient.
1

Emergency now

Use emergency care for severe, sudden, rapidly worsening, or life-threatening symptoms.

2

See a doctor

Book a professional medical evaluation if symptoms persist, worsen, recur often, affect daily activities, or occur in a high-risk patient.

3

Learn safely

Use this article to understand possible causes, tests, treatment options, prevention, and questions to ask your clinician.

Before reading

RX Patient Tools

Use these quick guides before reading the article, or return to them when you need help preparing questions for a doctor.

Start here Choose the right pathway for symptoms, reports, medicines, or urgent warning signs. Disease article roadmap Read this topic step by step: meaning, symptoms, warning signs, diagnosis, treatment, prevention, and follow-up. Treatment planner Prepare questions about treatment choices, benefits, risks, side effects, and follow-up. Family & caregiver guide Organize symptoms, reports, medicines, questions, and follow-up safely. Nutrition & diet guide Prepare food, hydration, supplement, and medicine-timing questions safely. Prevention guide Organize risk factors, protective habits, screening, and warning signs. Recovery guide Prepare a safe plan for activity, rehabilitation, warning signs, and follow-up.

JavaScript is single threaded, that means only one statement is executed at a time. As the JS engine processes our script line by line, it uses this single Call-Stack to keep track of codes that are supposed to run in their respective order.

Definition

Like what a stack does, a data structure which records lines of executable instructions and executes them in LIFO manner. So say if the engine steps into a function foo(){ it PUSH-es foo() into the stack and when the execution of foo()return; } is over foo() is POP-ped out of the call-stack.

Multiple-sequential-execution- axios-request

EXERCISE 1: So from the above diagram shows how a typical line by line execution happens. When the script of three console.log() statements is thrown at JS —

  • Step 1: The console.log(“Print 1”) is pushed into the call stack and executed, once done with execution, it is then popped out of the stack. Now the stack is empty and ready for any next instruction to be executed.

  • Step 2: console.log(“Print 2”); // is the next instruction is pushed and the same thing repeats until

  • Step 3: is executed and there is nothing left to push and execute.

Lets take an example to understand it better, its a famous Interview question as well. In the logText() function, I am only doing console.log() three times.

const logText = () => {
    console.log('A');
    setTimeout(() => {
        console.log('B');
    }, 0);
    console.log('C');
}

logText()

The output A C B

Explanation – Even though, I am passing 0 to the setTimeout() for the waiting period, because setTimeout() invokes a callback function – this callback function will be passed to an Event Loop. And we we know that – The event loop as a process is a set of phases with specific tasks that are processed in a round-robin manner – so the callback function will go through those phases and ultimately get executed. But during this process Node being Node, will be non-blocking, and so would NOT block the next lines of code which is the third line < console.log(‘C’) >

Further Reading

https://medium.com/@siddharthac6/javascript-execution-of-synchronous-and-asynchronous-codes-40f3a199e687

Worker pool is an execution model that spawns and handles separate threads, which then synchronously perform the task and return the result to the event loop. The event loop then executes the provided callback with said result.

Problem Statement – I want to fire second request based on one value returned by the first request. So, axios.all will not resolve my probelem.

I can use async and await

 async function getData() {
      const firstRequest = await axios.get(`${<URL1>}`);
      data1 = firstRequest.data[0];
      if (data1){
          const secondRequest = await axios.get(`${<URL2>}`);
          data1 = secondRequest.data;
      }
      return data1;
  }

A very important use case of this is, when resetting password. Before resetting the password, I have to make sure, that the unique-link sent to the user is valid (Not expired and the same that was sent to him) – So, for this, in the same password-reset function, I have to first make an axios call to an API endpoint, which will validate that the link sent to the user is valid. And only if this API call returns a valid respoonse, I will fire the second API call to the endpoint to actually reset the password.

Extract from a PasswordReset Component production grade project below

 componentDidMount() {
    const parsed = queryString.parse(this.props.location.search);
    this.setState({
      emailFromURLParams: parsed.email,
      uidFromURLParams: parsed.uid
    });
  }

// Function to reset the password - It will fire two sequential axios request and based on first request's successful response value, will do the next axios request.
  passwordResetOnSubmit = async e => {
    e.preventDefault();

    const {
      emailFromURLParams,
      uidFromURLParams,
      newResetPassword,
      confirmNewPassword
    } = this.state;

    const firstRequest = await axios
      .post("/api/forgot-password/verify-uid-before-password-reset", {
        emailFromURLParams,
        uidFromURLParams
      })
      .catch(error => {
        if (error.response.status === 400) {
          this.setState({ openWrongDateRangeSnackBar: true });
        }
      });
    const userId = await (firstRequest && firstRequest.data);

    if (userId && newResetPassword === confirmNewPassword) {
      axios
        .put("/api/user/password-reset", {
          userId,
          newResetPassword
        })
        .then(() => {
          this.setState(
            {
              openNewItemAddedConfirmSnackbar: true,
              newResetPassword: "",
              confirmNewPassword: ""
            },

            () => {
              setInterval(function() {
                history.push("/login");
              }, 3000);
            }
          );
        })
        .catch(error => {
          if (error.response.status === 404) {
            this.setState({
              message: "Authentication failed. User not found."
            });
          } else if (error.response.status === 401) {
            this.setState({ message: "Authentication failed. Wrong Password" });
          } else if (
            error.response.status === 500 ||
            error.response.status === 422
          ) {
            this.setState({
              message:
                "Authentication failed. Only for Port authorized personnel"
            });
          }
        });
    }
  };
Use case (Sequential Execution with plain callback function and async-await) - Here in the below EDIT / PUT route - From Client side req.body, I am sending a JSON data which along with other info has a 'date' field. I had to format that 'date' from req.body (to "YYYY-MM-DD") with moment, before running findByIdAndUpdate(). Else mongoose was saving the date one day prior to what I was selecting in the DatePicker, and then subsequent API call for that date's data (after the EDIT) will NOT give me the correct edited data.
NOTE - The code is working EVEN WITHOUT async-await. But including async-await seems to be better for safely achieving the result.

req.body is as below

{
        "wharfage": 143,
        "berth_hire": 5,
        "other_services": 6,
        "port_dues": 20,
        "total": 26,
        "date": "2019-02-25"
}

The actual route code in Express backend

Alternative – 1 – With a wrapper function which will invoke a callback()

router.put("/:id", (req, res, next) => {
  let editedItem = req.body;

  // Have to do this extra date formatting step, to change the formatting of the 'date' field. Else mongoose was saving the date one day prior to what I was selecting in the DatePicker.
  // Wrapper function that will wrap the database call (the findByIdAndUpdate() query) within a callback function that gets executed after the database query has finished.
  const wrapperFunction = async (editItem, callback) => {
    editItem.date = await moment(editItem.date).format("YYYY-MM-DD");
    if (typeof callback === "function") {
      callback();
    }
  };

  wrapperFunction(editedItem, () => {
    Revenue.findByIdAndUpdate(req.params.id, editedItem, { new: true }).exec(
      (err, record) => {
        if (err) {
          console.log(err);
          return next(err);
        } else {
          res.status(200).json(record);
        }
      }
    );
  });
});

Alternative – 2 for the above EDIT (PUT) route function (with an extra database call ) – this code was working

router.put("/:id", (req, res, next) => {
  let editedItem = req.body;
  Revenue.findById(req.params.id, (err, result) => {
    if (err) {
      console.log(err);
    } else {
      editedItem.date = moment(editedItem.date).format("YYYY-MM-DD");
    }
  }).then(() => {
    Revenue.findByIdAndUpdate(req.params.id, editedItem, { new: true }).exec(
      (err, record) => {
        if (err) {
          console.log(err);
          return next(err);
        } else {
          res.status(200).json(record);
        }
      }
    );
  });
});

Alternative-2 for the EDIT (PUT) route function above – Here, I am just plain formatting the date without resorting to any technique to make the next db-call function to wait. While its working the solution with async-await seems to be better for safely achieving the same.

router.put("/:id", (req, res, next) => {
  let editedItem = req.body;
  editedItem.date = moment(editedItem.date).format("YYYY-MM-DD");

  Revenue.findByIdAndUpdate(req.params.id, editedItem, { new: true }).exec(
    (err, record) => {
      if (err) {
        console.log(err);
        return next(err);
      } else {
        res.status(200).json(record);
      }
    }
  );
});

A specific Use Case –

Here in the below backend Express Route – I have to capture visitor data (after OTP was sent and OTP Mongodb schema updated with that latest OTP) when a visitor to the site downloads data.

But I need to first pick the latest OTP (that was generated and saved in mongodb) from the already saved database before comparing with the otp input by the user when prompted.

router.route("/visitor/:id").put((req, res, next) => {
  let visitorData = req.body;
  let visitorEmail = req.body.company_email;
  let latestOtp = [];

  // Wrapper function that will wrap the database call (the find() query) in a function and pass it a callback function that gets executed after the database query has finished.
  // Also always make sure the callback is indeed a function, without this check, if the findLatestOTP() is called either without the callback function as a parameter OR in place of a function a non-function is passed, our code will result in a runtime error.
  function findLatestOTP(mongoCollection, callback) {
    mongoCollection
      .find({ visitor_email: visitorEmail })
      .limit(1)
      .sort({ createdAt: -1 })
      .exec((err, record) => {
        if (err) {
          console.log(err);
        } else {
          latestOtp.push(record[0].generated_otp);
          if (typeof callback === "function") {
            callback();
          }
        }
      });
  }

  findLatestOTP(OTP, function() {
    if (req.body.otpReceivedByVisitor !== latestOtp[0]) {
      return res
        .status(401)
        .send({ success: false, msg: "Incorrect Code was input" });
    } else {
      DOCUMENTMODAL.findById(req.params.id, (err, record) => {
        if (err) {
          console.log(err);
        }
        record.visitor.push(visitorData);
        record.save((err, updatedRecord) => {
          if (err) {
            return next(err);
          }
          res.status(200).send(updatedRecord);
        });
      });
    }
  });
});

Some related Explanation –

JavaScript is single threaded, that means only one statement is executed at a time. As the JS engine processes our script line by line, it uses this single Call-Stack to keep track of codes that are supposed to run in their respective order.

Like what a stack does, a data structure which records lines of executable instructions and executes them in LIFO manner. So say if the engine steps into a function foo(){ it PUSH-es foo() into the stack and when the execution of foo()return; } is over foo() is POP-ped out of the call-stack.

 

Further Reading

https://stackoverflow.com/questions/47343225/making-2-sequential-requests-with-axios-second-request-depends-on-the-response

Doctor visit helper

Prepare before seeing a doctor

A simple rural-patient checklist to help you explain symptoms clearly, ask better questions, and avoid unsafe self-treatment.

Safety note: This is not a prescription or diagnosis. For severe symptoms, pregnancy danger signs, children with serious illness, chest pain, breathing difficulty, stroke-like weakness, or major injury, seek urgent care.

Which doctor may help?

General physician, urologist, nephrologist, or gynecologist depending on symptoms.

What to tell the doctor

  • Write burning, frequency, fever, flank pain, blood in urine, pregnancy, diabetes, and previous UTI history.

Questions to ask

  • Is this UTI, stone, prostate problem, diabetes-related, or another cause?
  • Do I need urine culture before antibiotics?

Tests to discuss

  • Urine routine/microscopy
  • Urine culture for recurrent/severe infection or treatment failure
  • Blood sugar and kidney function when indicated
  • Ultrasound if stone/obstruction/recurrent symptoms

Avoid these mistakes

  • Avoid self-starting antibiotics; wrong antibiotic can cause resistance.
  • Seek urgent care for fever with flank pain, pregnancy, vomiting, confusion, or inability to pass urine.

Medicine safety and first-aid guide

This section is for patient education only. It does not replace a doctor, pharmacist, or emergency care.

Safe first steps

  • Avoid heavy lifting, sudden bending, and prolonged bed rest.
  • Use comfortable posture and gentle movement as tolerated.
  • Discuss physiotherapy, X-ray, or MRI only when clinically needed.

OTC medicine safety

  • For mild back pain, pain-relief medicine may be discussed with a doctor or pharmacist.
  • Avoid repeated painkiller use if you have kidney disease, stomach ulcer, uncontrolled blood pressure, or are taking blood thinners.

Avoid these mistakes

  • Do not start antibiotics without a proper medical decision.
  • Do not use steroid tablets or injections casually for quick relief.
  • Do not delay emergency care because of home remedies.

Get urgent help if

  • Back pain with leg weakness, numbness around private area, loss of urine/stool control, fever, cancer history, or major injury needs urgent care.
Medicine names, dose, and timing must be decided by a qualified clinician or pharmacist after checking age, pregnancy, allergy, other diseases, and current medicines.

For rural patients and family caregivers

Patient health record and symptom diary

Write your symptoms, medicines already taken, test results, and questions before visiting a doctor. This note stays on your device unless you print or copy it.

Doctor to discuss: Doctor / qualified healthcare provider
Tests to discuss with doctor
  • Basic vital signs: temperature, pulse, blood pressure, oxygen level if needed
  • Relevant blood, urine, imaging, or specialist tests only after clinical assessment
Questions to ask
  • What is the most likely cause of my symptoms?
  • Which warning signs mean I should go to emergency care?
  • Which tests are really needed now?
  • Which medicines are safe for my age, pregnancy status, allergy, kidney/liver/stomach condition, and current medicines?

Emergency warning signs such as chest pain, severe breathing difficulty, sudden weakness, confusion, severe dehydration, major injury, or loss of bladder/bowel control need urgent medical care. Do not wait for online information.

Safe pathway to proper treatment

Care roadmap for: Multiple-sequential-execution- axios-request

Use this simple roadmap to understand the next safe steps. It is educational and does not replace examination by a doctor.

Go to emergency care if you notice:
  • Severe or rapidly worsening symptoms
  • Breathing difficulty, chest pain, fainting, confusion, severe weakness, major injury, or severe dehydration
Doctor / service to discuss: Qualified healthcare provider; specialist depends on symptoms and examination.
  1. Step 1

    Check danger signs first

    If danger signs are present, seek emergency care and do not wait for online information.

  2. Step 2

    Record the symptom story

    Write when symptoms started, severity, medicines already taken, allergies, pregnancy status, and test results.

  3. Step 3

    Visit a qualified clinician

    A doctor, nurse, or qualified healthcare provider can examine you and decide which tests or treatment are needed.

  4. Step 4

    Do only useful tests

    Do tests after clinical assessment. Avoid unnecessary tests, random antibiotics, or repeated medicines without diagnosis.

  5. Step 5

    Follow up and return early if worse

    If symptoms worsen, new warning signs appear, or treatment is not helping, return for review quickly.

Rural patient practical tips
  • Take a written symptom diary and all previous prescriptions/test reports.
  • Do not hide medicines already taken, even herbal or over-the-counter medicines.
  • Ask which warning signs mean urgent referral to hospital.

This roadmap is for education. A real diagnosis and treatment plan requires history, examination, and clinical judgment.

RX Patient Help

Ask a health question safely

Write your symptom story. A health professional or site editor can review it before any answer is prepared. This box is not for emergency care.

Emergency first: Severe chest pain, breathing trouble, unconsciousness, stroke signs, severe injury, heavy bleeding, or rapidly worsening symptoms need urgent local medical care now.

Frequently Asked Questions

Is this article a replacement for a doctor?

No. It is educational content only. Patients should consult a qualified clinician for diagnosis and treatment.

When should I seek urgent care?

Seek urgent care for severe symptoms, rapidly worsening condition, breathing difficulty, severe pain, neurological changes, or any emergency warning sign.

A global war against illness

Help this medical guide reach someone who may need it

Share reliable health information with a patient, family member, caregiver, or colleague. Reading and awareness can help people ask better questions and seek appropriate care.

Continue exploring

Explore this topic across the RX Medical Library

Open a focused A–Z pathway or continue with closely related indexed articles. These links are educational and do not replace personal medical care.

Search this topic
Diseases A–Z Drugs A–Z Lab Tests A–Z Cancer A–Z
Diseases A–Z

40 Emotional Intelligence Quotes

Distinguished intelligence researcher Howard Gardner (1999) knew this when he proposed his theory of multiple intelligences. Many…