首页 > 解决方案 > 有没有办法对函数调用进行排队?

问题描述

为了在结帐过程中与后端通信,我具有异步功能:

create():在后端创建购物车。当用户转到结帐页面时调用。

update():在后端编辑购物车。当用户编辑购物车时调用。

confirm():在后端确认购买。当用户下订单时调用。

update()取决于create()的响应,confirm()取决于create() / update()的响应

用户可以在另一个功能未完成时调用一个功能,例如在转到结帐页面后不久编辑购物车。由于依赖关系,这会导致问题。

我目前已经通过使用 bools processingshouldUpdateshouldConfirm半解决了这个问题。

有没有办法通过使用队列来实现下一个函数调用等待前一个函数调用完成?

var processing = false // Set true when a function is executing
var shouldUpdate = false // Set true when user edits cart
var shouldConfirm = false // Set true when user taps "Purchase"
var checkoutID = ""

func create() {
    processing = true
    APIClient.sharedClient.createShoppingCart() {
    (checkoutID, error) in
       ...
       processing = false // Finished with network call
       if shouldUpdate { // if edit was done while create() is running
           update()
           shouldUpdate = false
       }
       if shouldConfirm { // if user tapped "Purchase" while create() is running
           confirm()
       }
    }
}

func update() { // Called from view controller or create()
    if processing {return}
    processing = true
    APIClient.sharedClient.updateShoppingCart(forCheckoutID: checkoutID) {
    (error) in
       ...
       processing = false // Finished with network call
       if shouldConfirm { // if user tapped "Purchase" while update() is running
           confirm()
       }

    }
}

func confirm() { // Called from view controller or create()/update()
    if processing {return}
    APIClient.sharedClient.confirmPurchase(forCheckoutID: checkoutID) {
    (error) in
       ...
       /// Finish order process
    }
}

标签: swiftswift4

解决方案


您可以使用调度组

let apiDispatchGroup = DispatchGroup()

func asyncCall1() {
    apiDispatchGroup.enter()
    print("Entered")
    DispatchQueue.main.asyncAfter(deadline: .now()+3) {
        /// After 3 Second it will notify main Queue
        print("Task 1 Performmed")
        /// Let's notify
        apiDispatchGroup.leave()
    }

    apiDispatchGroup.notify(queue: .main) {
        /// Perform task 2
        asyncCall2()
    }
}

func asyncCall2() {
    print("Task 2")
}

推荐阅读