Future/Await 和 Async/Await 有什么区别
What is the difference of Future/Await and Async/Await
在 Scala 和其他编程语言中,可以使用 Futures 和 Await。
(在实际代码中,人们会使用例如 zip+map 而不是 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()
}
Await 是阻塞的,而 async 是 非阻塞。 Await 在当前线程中等待完成任务,而 async 不会阻塞当前线程并在后台运行。
我不知道 JavaScript。在 Scala 中,来自 scala.concurrent 包的 Await 用于阻塞主线程。还有另一个名为 scala-async 的库用于在 async 块中使用 await。
如果你使用scala-async,那么你需要在async中调用await
Scala 中的“Await.result
”函数是"blocking",这意味着调用线程将暂停,直到等待的 Future 完成,此时它将使用返回值恢复。
在高负载的系统中暂停线程可能代价高昂,因为线程上下文必须保存在内存中,这可能会导致缓存未命中等。因此,阻塞线程在并发编程中被认为是不好的做法.
Javascript 中的 async / await
语法是非阻塞的。当 async
函数调用“await
”时,它被转换为 Future,并放入执行队列。当 awaited
未来完成时,调用函数被标记为准备执行,它将在稍后的某个时间点恢复。重要的区别是在此模型中不需要暂停任何线程。
在 Scala 中有许多实现 async / await
语法的库,包括 https://github.com/scala/scala-async
进一步阅读
- PRASAD、PATIL 和 MILLER 合着的 Futures and Promises 一书很好地介绍了阻塞和非阻塞操作。
在 Scala 和其他编程语言中,可以使用 Futures 和 Await。
(在实际代码中,人们会使用例如 zip+map 而不是 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()
}
Await 是阻塞的,而 async 是 非阻塞。 Await 在当前线程中等待完成任务,而 async 不会阻塞当前线程并在后台运行。
我不知道 JavaScript。在 Scala 中,来自 scala.concurrent 包的 Await 用于阻塞主线程。还有另一个名为 scala-async 的库用于在 async 块中使用 await。
如果你使用scala-async,那么你需要在async中调用await
Scala 中的“Await.result
”函数是"blocking",这意味着调用线程将暂停,直到等待的 Future 完成,此时它将使用返回值恢复。
在高负载的系统中暂停线程可能代价高昂,因为线程上下文必须保存在内存中,这可能会导致缓存未命中等。因此,阻塞线程在并发编程中被认为是不好的做法.
Javascript 中的 async / await
语法是非阻塞的。当 async
函数调用“await
”时,它被转换为 Future,并放入执行队列。当 awaited
未来完成时,调用函数被标记为准备执行,它将在稍后的某个时间点恢复。重要的区别是在此模型中不需要暂停任何线程。
在 Scala 中有许多实现 async / await
语法的库,包括 https://github.com/scala/scala-async
进一步阅读
- PRASAD、PATIL 和 MILLER 合着的 Futures and Promises 一书很好地介绍了阻塞和非阻塞操作。