Home > Blockchain >  How to use functions in order?
How to use functions in order?

Time:08-05

I want to use some functions. But it works by randomly.

func first() {
    // using alamofire 
    case .success():
    ...
        print("1")
    }
func second() {
    // using alamofire
    ...
    case .success():
        print("2")
        tableView.reloadData()
    }

@IBAcition func click(_ sender: Any) {
    first()
    second()
    }

If I click the button. I expect always print : 1 2. But It prints sometime 2 1. How should I do?

CodePudding user response:

This is because you are using async code, move invoking of the second func to the .success() block of first func like so:

func first() {
    // using alamofire 
    case .success():
    ...
        print("1")
        second()
    }

That way you will be sure that second func is only called after first func fulfills

CodePudding user response:

func first(completion: @escaping(_ success:Bool) -> Void) {
    // using alamofire
    case .success():
            print("1")
         completion(true)
     case .failure():
         completion(false)
    }
func second(completion: @escaping(_ success:Bool) -> Void) {
   
    case .success():
         print("2")
         completion(true)
    case .failure():
         completion(false)
}

@IBAcition func click(_ sender: Any) {
    first { success in // first func executed
        if success { // first func success is true
            second { success in
                if success { // second func success is true
                    print("do something now")
                } else {
                    print("2nd func failed")
                }
            }
        } else {
            print("1st func failed")
        }
    }
}

CodePudding user response:

This is more about Asynchronous call understanding than a code issue. When making Asynchronous calls, be it an API call over the network or locally, you cannot be sure of the order it will be returned in.

For example, when calling first and second, it might be possible that the second call is returned earlier than the first. Thus creating the issue you are facing.

To solve the issue you can try the answer provided by Zeeshan Ahmed

  • Related