为了在结帐过程中与后端进行通信,我有异步功能:
create(( :在后端创建购物车。当用户转到结帐页面时调用。
update(( : 在后端编辑购物车。当用户编辑购物车时调用。
confirm(( : 在后端确认购买。在用户下订单时调用。
update(( 依赖于 create(( 的响应,confirm(( 依赖于 create((/update(( 的响应
用户可以在另一个函数未完成时调用一个函数,例如在结帐页面后不久编辑购物车。由于依赖关系,这会导致问题。
我目前已经通过使用布尔处理来半解决它,应该更新并应该确认。
有没有办法通过使用队列来实现,其中下一个函数调用等到上一个函数调用完成?
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
}
}
我个人使用 PromiseKit - 不错的文章一般在这里,在这里包装异步 - 以及如何在这里承诺
// your stack
var promises = [];
// add to your stack
promises.push(promise); // some promise func, see above links
promises.push(promise2);
// work the stack
when(fulfilled: promiseArray).then { results in
// Do something
}.catch { error in
// Handle error
}
类似解决方案的关键字:承诺、延迟、异步堆栈。
或:您可以实现以下内容:
有一个池,tupel数组:方法处理程序和布尔值(=执行true(
创建一个 func(1( 在另一个包装函数 (2( 中运行数组中的所有函数,该函数将在执行时设置 Tupels 布尔值。
func(1( 将等到图佩尔被更改, 然后抓住下一个。
您可以使用调度组
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")
}