Question Details

No question body available.

Tags

arrays swift async-await

Answers (1)

December 10, 2025 Score: 0 Rep: 535 Quality: Low Completeness: 80%

You’re running into this behavior because marking updateItemQuantity(...) as async does not make the call suspend — it simply wraps a callback-based API without turning it into a real suspendable function. Thus, await returns immediately and your loop continues without waiting for the network result.

To fix this, you need to bridge your callback API to Swift’s concurrency model. Use withCheckedContinuation so that await truly suspends until the response is ready. For example:

func updateItemQuantity(itemCode: String, quantity: Int) async -> Int {
    await withCheckedContinuation { continuation in
        Service.shared.updateItemQuantityApi(
            scannedCode: itemCode,
            quantity: quantity,
            expandedSearch: false,
            completion: { cartDTO in
                // … your existing cart-update logic …
                let count = Cart(from: cartDTO).cartItems.count
                continuation.resume(returning: count)
            },
            failure: { _, errorText in
                print("updateItemQuantity FAILED:", errorText)
                continuation.resume(returning: 0) // or handle error via continuation.resume(throwing:)
            }
        )
    }
}

Then your loop can properly await this and pause when needed:

while currentIndex < offlineItems.count {
    let offlineItem = offlineItems[currentIndex]
    let count = await updateItemQuantity(
        itemCode: offlineItem.scannedCode,
        quantity: offlineItem.quantity
    )

if count