I have a function lets call it "a" that runs some code and then returns a string "x" is updated in an asynchronous code block and then returned.
How would I go about making the program wait to return x until after the asynchronous code runs?
func a() -> String {
//code
//code
var x: String
async block {
x = "test"
}
return x
}
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. Code after each await expression can be thought of as existing in a .then callback.
await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves. So, if an asynchronous activity has already started, await will not have an effect on it.
If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.
Like everyone pointed out you can use a completion handler(closure
) to perform the operation. But you can also wait for the asynchronous call to be completed using DispatchSemaphore
. The semaphore obtains a lock when it makes wait
call and it's released when it's signaled from the asynchronous block.
func a()->String{
var x = ""
let semaphore = DispatchSemaphore(value: 0)
DispatchQueue.main.async {
x = "test"
semaphore.signal()
}
semaphore.wait()
return x
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With