How to Stop a Function From Running When It Is Called Again
Look for a Part to Finish in JavaScript
-
Sync
andAsync
in JavaScript - Use
callback
to Wait for a Function to Finish in JavaScript - Use
promises
to Wait for a Role to Finish in JavaScript - Use
async/await
to Wait for a Function to Finish Before Continuing Execution
This tutorial volition introduce JavaScript Callbacks
, Promises
, and Async/await
and show y'all how to look for an async function to end before continuing the execution.
To understand what Promises
and Async/await
are, we start need to understand what the Sync
and Async
functions are in JavaScript.
Sync
and Async
in JavaScript
Synchronous programming executes one control at a time. When nosotros phone call a function that performs a long-running activeness, information technology will stop the program until it finishes.
JavaScript is traditionally single-threaded, even with multi-cores. We can get information technology to run tasks simply on a unmarried thread chosen the principal thread.
Such synchronous behavior is a limiting factor in the multi-threads but helps the user write codes without worrying almost concurrency problems.
While in asynchronous programming, the long-running action volition exist executed in another thread other than the chief thread, so the master execution is not blocked. When that long-running function finishes, the main plan is informed and gets access to the results.
Most I/O primitives in JavaScript are not-blocking. Network requests, file systems operations are all non-blocking operations. Being blocked is the exception in JavaScript.
Since JavaScript is based on asynchronous programming techniques, there are multiple approaches such as callbacks
, promises
and async/await
enabling yous to put your functions executions in sequence. So that a lawmaking-cake or a part won't be executed earlier another specific function finishes.
The above figure shows the clear variation between asynchronous and synchronous execution of ii functions.
Use callback
to Wait for a Part to Finish in JavaScript
If we have synchronous statements, then executing those statements afterward each other is straight forward.
function one(){ console.log("I am function Ane"); } role Two(){ console.log("I am function Two"); } i(); Two();
Output:
I am part One I am function Two
Suppose we desire to execute two functions, functionOne()
and functionTwo()
such that functionOne()
should exist executed after executing some asynchronus statements within functionTwo()
.
function functionOne(_callback){ // practise some asynchronus work _callback(); } function functionTwo(){ // do some asynchronus work functionOne(()=>{ console.log("I am a callback"); }); } functionTwo();
When executing the in a higher place lawmaking, the last thing printed in the console is I am a callback
. The famous callback
example is the setTimeout
function with a handler function to execute later on timing out.
function testCallBack(){ console.log("log before utilise setTimeout function"); setTimeout(()=>{ console.log("inside timeout"); },5000); console.log("log subsequently apply setTimeout office"); } testCallBack();
Output:
log before utilise setTimeout role log after use setTimeout function inside timeout
Use promises
to Wait for a Function to Finish in JavaScript
A promise
is an object representing the eventual fulfillment or failure of an asynchronous operation. Nosotros adhere the fulfillment callback to the promise
with one or more and so
statements, and when can call the mistake handler callback in the catch
.
doFirstThing() .then(consequence => doSecondThing(result)) .then(newResult => doThirdThing(newResult)) .then(finalResult => { console.log("The terminal event matter"+finalResult); }) .catch(failureCallbackfunction); }
To chain so
and take hold of
statements equally the above case is one of the promises' advantages. We promise to doSecondThing(result)
one time the doFirstThing()
is fulfilled. The arguments to the and then
are optional, merely required if you have to return a outcome.
In example there is an fault, the browser will look at the end of the chain for the catch
and execute it. Information technology is very similar to the famous effort-catch
.
The post-obit example volition aid us sympathize the promises
chains and show the states how we can await for a function with asynchronous beliefs to finish execution before we can continue execution.
var resolvedFlag = true; let mypromise = part functionOne(testInput){ console.log("Entered office"); return new Promise((resolve ,turn down)=>{ setTimeout( ()=>{ panel.log("Inside the promise"); if(resolvedFlag==true){ resolve("Resolved"); }else{ pass up("Rejected") } } , 2000 ); }); }; mypromise().so((res)=>{ console.log(`The function recieved with value ${res}`) }).take hold of((error)=>{ console.log(`Handling mistake every bit nosotros received ${error}`); });
Output:
Entered function Inside the promise The function received with value Resolved
Creating a hope tin can be as piece of cake as returning a new Promise()
. The Promise()
constructor receives a function as an argument, which should have two parameters - resolve
and reject
.
In instance our result is fulfilled, and we need to return the result, we employ the resolve()
function when succeeding in what nosotros were doing. But if an mistake happens and needs to exist handled, we use pass up()
to send the error to the catch
.
Nosotros fix the flag resolvedFlag = truthful
to simulate error handling in the catch
. If resolvedFlag
is fix to exist simulated
, the decline()
function is called, and the error is handled in the grab
block.
Output:
Entered function Within the promise Treatment fault as we received Rejected
Use async/await
to Wait for a Function to Finish Before Continuing Execution
Another fashion to wait for a function to execute earlier standing the execution in the asynchronous environment in JavaScript is to use async/wait
.
The async
function is the function that is declared past the async
keyword, while merely the await
keyword is permitted within the async
part and used to append the progress within the async function until the promise-based asynchronous operation is fulfilled or rejected.
The async
and look
keywords enable asynchronous, promise-based behavior in a cleaner style.
Let'south understand how async/await
works. The function we are waiting for should return an example of Promise class to wait for information technology to execute using the await keyword before calling it. As mentioned to a higher place, the part that contains the await
statement must be declared with the async
statement.
The following instance shows how to wait for that promise-based function to finish before continuing the execution.
function testAsync(){ render new Promise((resolve,decline)=>{ //here our function should be implemented setTimeout(()=>{ console.log("Howdy from within the testAsync function"); resolve(); ;} , 5000 ); }); } async function callerFun(){ console.log("Caller"); await testAsync(); panel.log("After waiting"); } callerFun();
Output:
Caller Howdy from inside the testAsync function After waiting
Write for u.s.
DelftStack manufactures are written by software geeks similar y'all. If you also would like to contribute to DelftStack past writing paid manufactures, you can bank check the write for united states page.
Related Article - JavaScript Promises
Source: https://www.delftstack.com/howto/javascript/javascript-wait-for-function-to-finish/
0 Response to "How to Stop a Function From Running When It Is Called Again"
Postar um comentário