Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference of Future/Await and Async/Await

In Scala and other programming languages one can use Futures and Await.

(In real code one would use e.g. zip+map instead of Await)

def b1() = Future { 1 }
def b2() = Future { 2 }

def a() = Future {
  Await.result(b1(),Duration.inf) + Await.result(b2(),Duration.inf)
}

What is the difference to Async/Await in Javascript/Scala?

async function b1() { return 1 }
async function b2() { return 3 }

async function a() { 
  return await b1() + await b2()
}
like image 401
KingOfCoders Avatar asked Apr 23 '18 08:04

KingOfCoders


Video Answer


2 Answers

The "Await.result" function in Scala is "blocking", which means that the calling thread will be paused until the awaited Future is completed, at which point it will resume with the returned value.

Pausing a thread can be expensive in a system under high load, as the thread context has to be saved in memory, and it can cause cache misses etc.. Blocking threads is considered poor practice in concurrent programming for that reason.

The async / await syntax in Javascript is non-blocking. When an async function invokes "await", it is converted into a Future, and placed into the execution queue. When the awaited future is complete, the calling function is marked as ready for execution and it will be resumed at some later point. The important difference is that no Threads need to be paused in this model.

There are a number of libraries which implement the async / await syntax in Scala, including https://github.com/scala/scala-async

Further reading

  • The Futures and Promises book by PRASAD, PATIL, AND MILLER has a good introduction to blocking and non-blocking ops.
like image 166
Rich Avatar answered Oct 17 '22 02:10

Rich


Await is blocking while async is non blocking. Await waits in the current thread to finish the task while async won't block the current thread and runs in background.

I don't have idea about JavaScript. In Scala Await from scala.concurrent package is used for blocking main thread. There's another library called scala-async what is used for using await inside async block.

If you are using scala-async, then you need to call await inside async

like image 24
pramesh Avatar answered Oct 17 '22 04:10

pramesh