1

I'm trying to chain some backend calls to process a file, but the entire workflow needs some input from the user midway. I'm not sure how to pause the execution until the user clicks a button to "Continue" after working with a modal.

So the process is as follows:

  1. User selects a file which triggers an event to upload some data.
  2. I get the response from the previous call, open up a modal with a form. I need to pause here.
  3. Fill the form, click "Continue" button to resume promise chain.
  4. Trigger another call to submit more info to another endpoint.

So each of these steps relate to an HTTP request, using axios, but I'm having a hard time understanding how to chain the promises.

Right now I have something like:

onFileSelected(event) {
  // code here
  axios
    .post("")
    .then((res) => {
      // Here I need to open the modal, and wait for the button click
    })
    .then(() => {
      anotherMethod();
    });
}
Darryl Noakes
  • 2,207
  • 1
  • 9
  • 27
IvanS95
  • 5,364
  • 4
  • 24
  • 62
  • Are you using Vue? If you are, please state that in the question body in addition to tagging. – Darryl Noakes Aug 14 '23 at 23:03
  • 1
    `Here I need to open the modal, and wait for the button click` make a promise that resolves once the button is clicked - importantly, return that promise inside `.then` - without knowing your modal code, it's a bit difficult to help though – Jaromanda X Aug 14 '23 at 23:08
  • 2
    Have a look at [How can I use async / await in my function to wait for an event to fire on an input element](https://stackoverflow.com/a/75264023/1048572) – Bergi Aug 14 '23 at 23:20
  • @JaromandaX sorry, the modal code is just another axios call that should be triggered on the click of the same `Continue` button, I didn't think it was too relevant – IvanS95 Aug 14 '23 at 23:28
  • Just Call anotherMethod(); in Modal on button-"Yes" click + closeModal(). – Михаил Aug 15 '23 at 14:58

1 Answers1

1

Promises themselves don't provide a way to pause their execution, but you can achieve this using the async/await syntax. Create a custom promise that resolves when the user clicks the "Continue" button. Something like this,

async function onFileSelected(event) {
  try {
    const response = await axios.post("") // Upload data
    await showModalAndWaitForUserInteraction() // Pause and wait for user input

    await anotherMethod() // Continue after user interaction

    // Continue with the rest of your promise chain
    const anotherResponse = await axios.post("") // Submit more info to another endpoint
    // ...
  } catch (error) {
    // Handle errors here
  }
}

function showModalAndWaitForUserInteraction() {
  return new Promise((resolve) => {
    // Show the modal with button
    // ...modal logic
    // then resolve() 
  })
}
Nazrul Chowdhury
  • 1,483
  • 1
  • 5
  • 11