Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(async () => { })(); what is this?

async function test() {
  (async () => {            
    var a = await this.test1();
    var b = await this.test2(a);
    var c = await this.test3(b);  
    this.doThis(a,b,c);                              
  })();
}

What does it mean to put methods (test1,test2,test3) inside async () => {})()? I find it faster than

async function test() {          
  var a = await this.test1();
  var b = await this.test2(a);
  var c = await this.test3(b);  
  this.doThis(a,b,c); 
}

Any downside of using it?

like image 330
bbusdriver Avatar asked Jul 12 '19 20:07

bbusdriver


People also ask

What is async function used for?

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

What is async function in Python?

Asynchronous programming is a type of programming in which we can execute more than one task without blocking the Main task (function). In Python, there are many ways to execute more than one function concurrently, one of the ways is by using asyncio.

What does async mean JavaScript?

Asynchronous JavaScript: Asynchronous code allows the program to be executed immediately where the synchronous code will block further execution of the remaining code until it finishes the current one.

Why should I use async?

Asynchronous loops are necessary when there is a large number of iterations involved or when the operations within the loop are complex. But for simple tasks like iterating through a small array, there is no reason to overcomplicate things by using a complex recursive function.


1 Answers

Both return a promise but they return different promises.

The first will return a promise that may resolve before this.test1()'s result resolves.

The second returns a promise that only resolves after the final call to this.doThis(a,b,c);.

This has been called the "fire and forget pattern":

Often in application development you want a process to call another thread and continue the process flow, without waiting for a response from the called thread. This pattern is called the “fire and forget” pattern.

You can see this in

function logEventually(str) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(str);
      resolve(null);
    }, 0);
  });
}

async function a() {
  await logEventually('in a 1');
  await logEventually('in a 2');
  await logEventually('in a 3');
  return await logEventually('end of a');
}

async function b() {
  (async () => {
    await logEventually('in b 1');
    await logEventually('in b 2');
    await logEventually('in b 3');
  })();
  return await logEventually('end of b');
}

a();
b();
like image 147
Mike Samuel Avatar answered Sep 22 '22 08:09

Mike Samuel