2025-02-07 17:23:04
,某些文章具有时效性,若有错误或已失效,请在下方留言。This error occurs when you’ve tried to call an async function from a synchronous function, which is not allowed in Swift – asynchronous functions must be able to suspend themselves and their callers, and synchronous functions simply don’t know how to do that.
当您尝试从同步函数调用 async 函数时,会出现此错误,这在 Swift 中是不允许的 – 异步函数必须能够挂起自身及其调用者,而同步函数根本不知道如何执行此作。
You can see it with code like this:
你可以通过如下代码看到它:
func doAsyncWork() async {
print("Doing async work")
}
func doRegularWork() {
await doAsyncWork()
}
doRegularWork()
If your asynchronous work needs to be waited for, you don’t have much of a choice but to mark your current code as also being async
so that you can use await
as normal.
如果需要等待异步工作,则别无选择,只能将当前代码标记为async
,以便可以正常使用 await
。
However, sometimes this can result in a bit of an “async infection” – you mark one function as being async, which means its caller needs to be async too, as does its caller, and so on, until you’ve turned one error into 50.
但是,有时这可能会导致一些“异步感染”——您将一个函数标记为异步,这意味着它的调用者也需要是异步的,它的 调用者也需要是异步的,依此类推,直到您将一个错误变成 50 个错误。
In this situation, you can create a dedicated Task
to solve the problem. We’ll be covering this API in more detail later on, but here’s how it would look in your code:
在这种情况下,您可以创建专用Task
来解决问题。我们稍后将更详细地介绍此 API,但以下是它在代码中的外观:
func doAsyncWork() async {
print("Doing async work")
}
func doRegularWork() {
Task {
await doAsyncWork()
}
}
doRegularWork()
Tasks like this one are created and run immediately. We aren’t waiting for the task to complete, so we shouldn’t use await
when creating it.
像这样的任务会立即创建并运行。我们不会等待任务完成,因此在创建任务时不应使用 await
。