@torstha if you track the OK responses from each command then you can use the M400 command to wait for all movement to stop. You won't get an OK response from the M400 command until motion has stopped.
Alternatively, use the M409 command to read state.status in a loop and wait for it to become "idle".