How to exit loop in an async call?

vendrick

New Member
#1
Simplified version of my code is like this:
Mã:
var joined = false

for room in rooms {
    checkRoom() { // async func
        if room.player.count == 1 {
            join(room)
            joined = true
            // break doesnt work here
        }
    }

    if joined {
        break;
    }
}
I need to exit this loop because it is still checking other rooms after joining one. I want to stop checking rest of rooms when joined becomes true. But ofcourse it becomes true in async call only so my method does not work.

How can I exit this loop when joined becomes true?
 

Admin

Administrator
Thành viên BQT
#2
Async function call should be avoided inside loop. Suppose checkRoom() method makes API call internally. In that case, loop will run for all rooms and API requests for all rooms would be queued regardless of when you get response for each request.

Ideally you should replace loop with recursion. Call checkRoom() inside a function, let's call it mainFunction(), and wait for the response. If your criterion for joining room doesn't meet, then call your mainFunction() recursively which will make next call to checkRoom() function. Something like this:

Mã:
var rooms: Array<Room> = []
var currentRoomIndex: Int = 0

func mainFunction() {

        checkRoom() { // async func
            let room = rooms[currentRoomIndex]
            if room.player.count == 1 {
                join(room)
                joined = true
                break
            } else {
                currentRoomIndex += 1
                mainFunction()
            }
        }
}
Another way would be to add all your calls to checkRoom() function (probably API requests) to a queue and as soon as your room joining criterion meets, stop tasks/requests that are still pending in the queue.
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top