jos*_*ori 6 asynchronous swift
在斯威夫特 5.5 中:
以下 Swift 代码将出现编译器错误:“在不支持并发的函数中进行异步调用”。
// Swift
func hi() async {
print("hi")
}
func callAsyncHi() {
hi()
}
Run Code Online (Sandbox Code Playgroud)
在 Javascript 中,await 仅在 async function 中有效,但从普通 func 调用 async func 是有效的。因此下面的 Javascript 代码会异步打印“hi”。
// Javascript
async function hi() {
console.log("hi")
}
function callAsyncHi() {
hi()
}
callAsyncHi()
Run Code Online (Sandbox Code Playgroud)
我还发现如果没有wait或async let则无法调用 async func 。为什么Swift要这样设计呢?
You can invoke async function from normal function by wrapping the asynchronous call inside a task:
func hi() async {
print("hi")
}
func callAsyncHi() {
let task = Task {
await hi()
}
}
Run Code Online (Sandbox Code Playgroud)
This is similar to how you can invoke async methods in java script from synchrnous context, key difference being in Swift you have to explicitly specify it and inside Task you can invoke more than one async methods.
There are certain reasons behind a design like this. Key reason being in Swift all async methods are associated with tasks and support cooperative cancellation.
Swift concurrency uses a cooperative cancellation model. Each task checks whether it has been canceled at the appropriate points in its execution, and responds to cancellation in whatever way is appropriate.
By requiring async keyword Swift keeps track of the dependency chain of async calls and propagates cancellation event when it occurs (While as far as I know promises in JS doesn't support cancellation of promises). In the above code, you can invoke cancellation on task variable by keeping track of it.
现在第二个原因,在我看来更重要的是,通过要求显式调用,这使得审查代码变得更容易,因为我必须检查是否正确处理了此类调用的取消,而在 JS 的情况下,很难查明此类滥用。
jos*_*ori -2
我们自由地传递承诺/任务并做很多事情。
但是 Swift 的异步函数会返回??? 。
??? 被隐藏。我什至无法打印它的类型。
// swift compiler error: Expression is 'async' but is not marked with 'await'
func callAsyncHi() {
Task {
async let tmp = hi()
print(Mirror(reflecting: tmp).subjectType)
await tmp
}
}
Run Code Online (Sandbox Code Playgroud)
我想应该没有吧???。所以我们必须将 async func 与wait一起使用。
| 归档时间: |
|
| 查看次数: |
4540 次 |
| 最近记录: |