Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript : function that involves two functions

I’m trying to make a function call "sendAndMove" that involves two function inside.
And I want two functions executed in order of setting() —> goHome(). But when I wrote code like down below, it is exectued like goHome() —> setting(). So I used async/await to achieve to goal.

Is this problem happend because of asynchronous feature and Call stack?
And I want to know why setting() function doesn’t work if page changes.
Thanks a lot

function setting() {
        setFinalInfo((prev)=>{return{...prev,
          finalAddress: info.address,
          finalCode: info.code,
          finalDetailAddress: info.detailAddress,
          finalPostCode: info.postCode,
          finalExtraAddress: info.extraAddress}
        });
          
      }
      function goHome(){
        navigate("/")
      }
        
      function sendAndMove() {
        setting();
        goHome();
          
      }

So I Changed to code below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  function setting() {
        setFinalInfo((prev)=>{return{...prev,
          finalAddress: info.address,
          finalCode: info.code,
          finalDetailAddress: info.detailAddress,
          finalPostCode: info.postCode,
          finalExtraAddress: info.extraAddress}
        });
          
      }
      function goHome(){
        navigate("/")
      }
        
      async function sendAndMove() {   ***** Changed this part
        await setting();
        await goHome();
          
      }

>Solution :

What you actually want to do is ‘channel’ from a callback to an awaitable promise, something like this:

function setting() {
  return new Promise((resolve) => {
    setFinalInfo((prev) => {
      resolve({
        ...prev,
        finalAddress: info.address,
        finalCode: info.code,
        finalDetailAddress: info.detailAddress,
        finalPostCode: info.postCode,
        finalExtraAddress: info.extraAddress,
      });
    });
  });
}

function goHome() {
  navigate('/');
}

async function sendAndMove() {
  await setting();
  goHome();
}

Btw, you don’t need to await on goHome() since that is not an async function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading