UnluckyLAD
UnluckyLAD

Reputation: 179

How can I make a statement wait until a previous function is finished?

I've got an issue where window.open gets called too quickly and my other function doesn't finish and post in time in my onclick function.

I tried setting a timeout on the trackData() but it only worked on occasion and I didn't want to set a longer timeout.

onClick

   {() => {
       trackData();
       window.open("https:google.com", "_self");
    })

any ideas?

EDIT: The following works locally but doesn't track when in production. Tracking works EVERYTIME if "_self" is being replaced with "_blank" (which it cannot be)

  let postData = async(value) => {
       await tracker({
            action: value,
        })
    }

tracker just makes an axios post with the action

   <div
       className="exampleBTN"
       onClick={() =>  {
       postData("example").then(                         
       window.open("https://google.com", 
       "_self")
       )}
    }
    >
   </div>

Locally, I can see the data going into the database.

However, online it doesn't work. It only works if either of these are true:

I thought my async was wrong so I also tried the following:

 onClick={async () =>  {
 await postData("example").then(                            
 window.open("google.com", "_self"))
 }}

Upvotes: 0

Views: 939

Answers (2)

railgaadi
railgaadi

Reputation: 36

You can work with .then or async/await to do exactly this when action results in a Promise. Axios requests return Promises.

initiateAsynchronousAction()
  .then(result => console.log(result))

Callback inside the .then function will only be executed if the promise is fulfilled by the action executed by the async function.

Minor clarification: Note that inside the .then() you have to pass a callback function and not just immediately invoke actions you want to perform, even if you don't plan to use the result value. So it will be .then(result=> console.log('Inside callback!'))

and not .then(console.log('Inside callback!'))

Async-await is another way to write this, it is simply syntactic sugar, that is just an easier way to write it:

const foo = async () => {
  const result = await initiateAsynchronousAction()
  console.log(result)
}

The variable result will only be given the value once the Promise is resolved. That is, the assigning of the value will be awaited.

You can chain a .catch in the first case or envelop the task in a try-catch block to catch errors if the Axios promise is unfulfilled.

Upvotes: 1

sharun k k
sharun k k

Reputation: 467

you can use promise based approache here.use aysnc and await for that.

async function trackData(){
 ..... 
   let data = awiat your code 
.....
}

function call with promise

trackData().then(res=>{
  if(res ==="Success){
 window.open("https:google.com", "_self")
}
})

Upvotes: 1

Related Questions