Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for asynchronous block before continuing

Tags:

swift

swift3

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
}
like image 753
S. Doe Avatar asked Jun 13 '17 03:06

S. Doe


People also ask

How do you wait for async to finish?

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.

Can I call async function without await?

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.

Does await blocks the next line?

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.

What happens when we don't use await?

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.


1 Answers

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
}
like image 189
ebby94 Avatar answered Nov 15 '22 12:11

ebby94