Javascript Wait for Function to Finish Before Firing It Again
Await for a Function to Finish in JavaScript
-
SyncandAsyncin JavaScript - Utilize
callbackto Look for a Function to Stop in JavaScript - Apply
promisesto Wait for a Part to Stop in JavaScript - Use
async/awaitto Wait for a Function to Finish Earlier Standing Execution
This tutorial will introduce JavaScript Callbacks, Promises, and Async/expect and show you lot how to wait for an async part to finish before standing the execution.
To understand what Promises and Async/await are, nosotros showtime need to understand what the Sync and Async functions are in JavaScript.
Sync and Async in JavaScript
Synchronous programming executes 1 command at a fourth dimension. When we call a function that performs a long-running activity, it will end the program until it finishes.
JavaScript is traditionally single-threaded, even with multi-cores. We can become information technology to run tasks but on a unmarried thread chosen the main thread.
Such synchronous beliefs is a limiting gene in the multi-threads but helps the user write codes without worrying about concurrency problems.
While in asynchronous programming, the long-running activeness will be executed in another thread other than the main thread, so the main execution is non blocked. When that long-running function finishes, the main plan is informed and gets admission to the results.
Most I/O primitives in JavaScript are non-blocking. Network requests, file systems operations are all non-blocking operations. Beingness 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 you to put your functions executions in sequence. And then that a code-block or a function won't be executed before some other specific function finishes.

The above figure shows the clear variation betwixt asynchronous and synchronous execution of two functions.
Employ callback to Wait for a Part to Finish in JavaScript
If we accept synchronous statements, then executing those statements after each other is directly forward.
function one(){ panel.log("I am function Ane"); } function Two(){ console.log("I am role Two"); } ane(); Two(); Output:
I am office I I am function Two Suppose we desire to execute 2 functions, functionOne() and functionTwo() such that functionOne() should be executed subsequently executing some asynchronus statements inside functionTwo().
office functionOne(_callback){ // do some asynchronus work _callback(); } function functionTwo(){ // do some asynchronus work functionOne(()=>{ console.log("I am a callback"); }); } functionTwo(); When executing the above code, the last thing printed in the console is I am a callback. The famous callback case is the setTimeout function with a handler function to execute after timing out.
office testCallBack(){ panel.log("log before use setTimeout function"); setTimeout(()=>{ panel.log("inside timeout"); },5000); console.log("log afterwards use setTimeout function"); } testCallBack(); Output:
log before utilise setTimeout function log later use setTimeout function inside timeout Employ promises to Look for a Function to Finish in JavaScript
A hope is an object representing the eventual fulfillment or failure of an asynchronous operation. We attach the fulfillment callback to the promise with one or more then statements, and when tin phone call the error handler callback in the catch.
doFirstThing() .then(result => doSecondThing(result)) .then(newResult => doThirdThing(newResult)) .then(finalResult => { console.log("The terminal result thing"+finalResult); }) .catch(failureCallbackfunction); } To chain then and catch statements as the in a higher place example is ane of the promises' advantages. We hope to doSecondThing(consequence) once the doFirstThing() is fulfilled. The arguments to the and so are optional, but required if you have to return a result.
In case there is an fault, the browser will look at the end of the concatenation for the grab and execute it. Information technology is very similar to the famous try-catch.
The post-obit instance will help united states sympathize the promises bondage and prove usa how we can wait for a role with asynchronous beliefs to finish execution before nosotros tin can go on execution.
var resolvedFlag = true; let mypromise = function functionOne(testInput){ console.log("Entered function"); return new Promise((resolve ,reject)=>{ setTimeout( ()=>{ console.log("Inside the promise"); if(resolvedFlag==true){ resolve("Resolved"); }else{ reject("Rejected") } } , 2000 ); }); }; mypromise().then((res)=>{ console.log(`The function recieved with value ${res}`) }).grab((error)=>{ console.log(`Treatment error as we received ${error}`); }); Output:
Entered office Inside the promise The role received with value Resolved Creating a promise tin can be as easy as returning a new Promise(). The Promise() constructor receives a function as an argument, which should accept two parameters - resolve and reject.
In case our event is fulfilled, and we demand to return the result, we use the resolve() function when succeeding in what nosotros were doing. But if an error happens and needs to exist handled, we use decline() to send the error to the catch.
We set the flag resolvedFlag = truthful to simulate error handling in the take hold of. If resolvedFlag is set to be false, the decline() function is chosen, and the error is handled in the catch block.
Output:
Entered function Within the promise Treatment fault equally we received Rejected Use async/expect to Wait for a Function to Finish Before Standing Execution
Another way to wait for a role to execute earlier continuing the execution in the asynchronous environment in JavaScript is to use async/wait.
The async office is the function that is alleged past the async keyword, while simply the await keyword is permitted inside the async office and used to append the progress inside the async function until the promise-based asynchronous operation is fulfilled or rejected.
The async and await keywords enable asynchronous, promise-based behavior in a cleaner style.
Allow'south understand how async/await works. The function we are waiting for should return an example of Promise form to wait for it to execute using the await keyword before calling information technology. As mentioned to a higher place, the part that contains the wait statement must be declared with the async statement.
The following case shows how to wait for that promise-based function to finish before continuing the execution.
function testAsync(){ return new Promise((resolve,decline)=>{ //hither our function should be implemented setTimeout(()=>{ console.log("Hello from inside the testAsync role"); resolve(); ;} , 5000 ); }); } async role callerFun(){ panel.log("Caller"); await testAsync(); console.log("After waiting"); } callerFun(); Output:
Caller Hello from inside the testAsync role After waiting Write for us
DelftStack manufactures are written by software geeks like you. If you lot also would like to contribute to DelftStack past writing paid articles, y'all tin cheque the write for united states of america page.
Related Commodity - JavaScript Promises
Source: https://www.delftstack.com/howto/javascript/javascript-wait-for-function-to-finish/
Post a Comment for "Javascript Wait for Function to Finish Before Firing It Again"