Code with sequential execution

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.

Article Summary

Transform the following code with sequential execution. I want to fire second request based on one value returned by the first request. For example, the Fetch API provides an interface for making network requests, returning Promises for us to resolve. To use it to get the current weather in Long Beach, we chain together two then callbacks: fetch("https://api.com/values/1") .then(response => response.json()) .then(json => console.log(json)); In...

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.
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.

Transform the following code with sequential execution. I want to fire second request based on one value returned by the first request.

Definition

For example, the Fetch API provides an interface for making network requests, returning Promises for us to resolve. To use it to get the current weather in Long Beach, we chain together two then callbacks:

fetch("https://api.com/values/1")
  .then(response => response.json())
  .then(json => console.log(json));

In the first, we create a callback function to receive the Response object and return back its JSON data. In the second, we create a callback that receives that data and then logs it to the console.

Need to wrap it inside an async function to make the async-await mechanism work.

const request = async () => {
  const response = await fetch("https://api.com/values/1");
  const json = await response.json();
  console.log(json);
};

request();

In the first line, we make a GET request to https://api.com/values/1. Instead of continuing to the next line, we wait for the request to finish, hence await. When it finishes, it passes the resolved value to the response variable.

In the second line, we get the JSON version of the response. Again, we use await so we can wait for it to complete (or fail) and then pass the result to the json variable.

By wrapping the logic inside an async function, we can replace the then callbacks with await statements. The effect, the code pauses execution on those lines until the Promises resolve! Asynchronous programming becomes synchronous!

Async/Await enables us to write asynchronous code in a synchronous fashion, which produces cleaner and easier-to-understand logic. Under the hood, it’s just syntactic sugar using generators and yield statements to “pause” execution. In other words, async functions can “pull out” the value of a Promise even though it’s nested inside a callback function, giving us the ability to assign it to a variable!

1st Basic Implementation

handleForm = async event => {
  this.setState({ isProcessing: true });
  const response = await client.sendApiRequest({
    value1: event.target.elements.field1.value,
    value2: event.target.elements.field2.value
  });
  if (response.ok) this.setState({ isProcessing: false });
};

the code above is totally fine. The syntactic sugar of async/await is backed by Promises which means we could also look at our code as doing something like this:

handleForm = event => {
    this.setState({ isProcessing: true });
    client.sendApiRequest({
      value1: event.target.elements.field1.value,
      value2: event.target.elements.field2.value,
    }).then(response => {
      if (response.ok)
        this.setState({ isProcessing: false });
    });
  });
}

The first part of that promise is going to execute in what is essentially a synchronous manner. That means we are safe to pass the event values as arguments.

However, it’s important to recognize that this does not mean that accessing the event values anywhere in an async function is okay. Take for example what would happen if we needed access the event after the API request.

handleForm = async event => {
  this.setState({ isProcessing: true });
  const response = await client.sendApiRequest({
    value1: event.target.elements.field1.value,
    value2: event.target.elements.field2.value
  });
  if (response.ok) {
    this.setState({
      isProcessing: false,
      value1: event.target.elements.field1.value,
      value2: event.target.elements.field2.value
    });
  }
};

Now we’re accessing the event after the await, which is like accessing it in the .then chain of a promise. We would be accessing the event asynchronously now.

Here’s that same event written as promises again:

handleForm = event => {
  return new Promise((resolve, reject) => {
    this.setState({ isProcessing: true });
    client
      .sendApiRequest({
        value1: event.target.elements.field1.value,
        value2: event.target.elements.field2.value
      })
      .then(response => {
        if (response.ok) {
          this.setState({
            isProcessing: false,
            value1: event.target.elements.field1.value,
            value2: event.target.elements.field2.value
          });
        }
      });
  });
};
Problem - It a common requirement in React to sequentially execute codes ONLY after multiple API calls have given their result to the component. Here, I have two different API points that I am trying to get and restructure after getting the data : students and scores. They are both an array of objects.So the goal is : first, get students and scores, and second, with students and scores saved in state, I will modify them and create a new state based on students and scores state. In short, I have 3 functions: getStudents, getScores, and rearrangeStudentsAndScores. getStudents and getScores need to finish before rearrangeStudentsAndScores can run.

[I have not tested this code yet in an actual app]

// Refactor getStudents and getScores to return  Promise for their response bodies
function getStudents() {
  return fetch(`api/students`, {
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json"
    }
  }).then(response => response.json());
}

function getScores() {
  return fetch(`api/scores`, {
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json"
    }
  }).then(response => response.json());
}

// Request both students and scores in parallel and return a Promise for both values.
// `Promise.all` returns a new Promise that resolves when all of its arguments resolve.
function getStudentsAndScores() {
  return Promise.all([getStudents(), getScores()]);
}

// When this Promise resolves, both values will be available. And because getStudentsAndScores() returns a Promise, I can chain a .then() function to it.
getStudentsAndScores().then(([students, scores]) => {
  // both have loaded!
  console.log(students, scores);
});

In this approach I make both requests at the same time.

Source

https://stackoverflow.com/questions/44980247/how-to-finish-all-fetch-before-executing-next-function-in-react

Further Reading

1> https://medium.com/@ian.mundy/async-event-handlers-in-react-a1590ed24399 2> https://medium.com/@tkssharma/writing-neat-asynchronous-node-js-code-with-promises-async-await-fa8d8b0bcd7c – Very Good

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

  • Rest, drink safe water, and observe symptoms carefully.
  • Keep a written note of symptoms, duration, temperature, medicines already taken, and allergy history.
  • Seek medical care quickly if symptoms are severe, worsening, or unusual for the patient.

OTC medicine safety

  • For mild pain or fever, ask a registered pharmacist or doctor before using common over-the-counter pain/fever medicines.
  • Do not combine multiple pain medicines without advice, especially if you have kidney disease, liver disease, stomach ulcer, asthma, pregnancy, or take blood thinners.
  • Do not give adult medicines to children unless a qualified clinician advises it.

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

  • Severe symptoms, confusion, fainting, breathing difficulty, chest pain, severe dehydration, or sudden weakness need urgent medical 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: Code with sequential execution

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.