How to make a normal java script function asynchronous?

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 ... ');

4 thoughts on “How to make a normal java script function asynchronous?”

  1. If async/await syntax is not available one can opt to manually wrap the function into a promise

    function call() {
      return new Promise(res => {
        let counter = 0;
        for (let i = 0; i < 40000; i++) {
          for (let j = 0; j < 50000; j++) {
            counter++;
          }
        }
        res(counter);
      })
    }
    
    call().then((value) => console.log(value));
    console.log('loading . . . ');
    Reply
  2. 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.
    • An async function always returns a promise. It wraps any returned value in Promise.resolve(returnval). However, when an uncaught error is thrown inside the async function it wraps the return value in Promise.catch(returnval).
    • Inside async functions you can use the 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:

    const randomProm = new Promise((resolve, reject) => {
        if (Math.random() > 0.5) {
            resolve("Succes");
        } else {
            reject("Failure");
        }
    });
    
    // async keyword creates an async function which returns a promise 
    async function ansyncExample() {
    
        try {
            const outcome = await randomProm;
            console.log(outcome);
        } catch (error) {
            console.log(error);
        }
    
        // This return value is wrapped in a promise
        return 'AsyncReturnVal';
    }
    
    // ansyncExample() returns a promise, we can call its corresponding then method
    ansyncExample().then((value) => {
        console.log(value);
    });
    
    console.log('I get executed before the async code because this is synchronous');
    Reply
  3. Please try this:

    async function call() {
      let counter = 0;
      for (let i = 0; i < 40000; i++) {
        for (let j = 0; j < 50000; j++) {
          counter++;
        }
      }
      return counter;
    }
    
    
    call().then((value) => console.log(value));
    
    console.log('loading . . . ');
    Reply

Leave a Comment