search

Home  >  Q&A  >  body text

How to wait for button click in Promise chain to pause execution?

<p>I'm trying to chain some backend calls to process files, but the whole workflow requires the user to provide some input halfway through. I'm not sure how to pause execution until the user clicks a button "<code>Continue</code>" so that it can continue working. </p> <p>So the process is as follows:</p> <ol> <li>The user selects a file and triggers an event to upload some data. </li> <li>I get the response from the previous call, opening a modal with a form. I need to pause here. </li> <li>Fill out the form and click the <code>Continue</code> button to continue the promise chain. </li> <li>Trigger another call to submit more information to another endpoint. </li> </ol> <p>So each of these steps involves an HTTP request, using <code>axios</code>, but I'm having trouble understanding how to chain these promises. </p> <p>Now I have code similar to: </p> <pre class="brush:js;toolbar:false;">onFileSelected(event) { // code here axios .post("") .then((res) => { //Here I need to open the modal box and wait for the button to be clicked }) .then(() => { anotherMethod(); }); } </pre> <p><br /></p>
P粉170438285P粉170438285492 days ago773

reply all(1)I'll reply

  • P粉277824378

    P粉2778243782023-08-16 10:20:51

    Promise itself does not provide a method to pause execution, but you can use async/await syntax to achieve this. Create a custom Promise that resolves when the user clicks the "Continue" button. like this:

    async function onFileSelected(event) {
      try {
        const response = await axios.post("") // 上传数据
        await showModalAndWaitForUserInteraction() // 暂停并等待用户输入
    
        await anotherMethod() // 用户交互后继续执行
    
        // 继续执行剩余的Promise链
        const anotherResponse = await axios.post("") // 提交更多信息到另一个终点
        // ...
      } catch (error) {
        // 在这里处理错误
      }
    }
    
    function showModalAndWaitForUserInteraction() {
      return new Promise((resolve) => {
        // 显示带有按钮的模态框
        // ...模态框逻辑
        // 然后 resolve() 
      })
    }
    

    reply
    0
  • Cancelreply