Firstly The code below prints the value from the call()
function which it returns though it takes some time to execute, then it prints the next line.
But I want to make it async behavior so that it first outputs the last line(which execution time is less) than the previous (higher exec time). How can I do that?
function call() {
let counter = 0;
for (let i = 0; i < 40000; i++) {
for (let j = 0; j < 50000; j++) {
counter++;
}
}
return counter;
}
console.log(call());
console.log('loading ... ');
By adding the key word
async
before the fonction so it becomesi hope it will helps
If async/await syntax is not available one can opt to manually wrap the function into a promise
Asynchronous functions
Asynchronous functions are built on top of promises. They allow a more convenient use of Promises. Asynchronous functions have the following properties:
async
before a function declaration/expression turns the function into an async function. As the name suggests async function are executed asynchronously.Promise.resolve(returnval)
. However, when an uncaught error is thrown inside the async function it wraps the return value inPromise.catch(returnval)
.await
keyword which can be used before any promise.await
makes JS code execution stop until the promise is settled. i.e. The promise has to be either fulfilled or rejected until any further code inside the async function is executed.await
either returns the value of the fulfilled promise, or throws an error in the case of a rejected promise. We can use regular try-catch to catch the error.Let’s clarify this with some examples:
Example1:
Please try this: