Ramanan Nathamuni
Ramanan Nathamuni

Reputation: 11

Asynccallback with in for loop

I am new in GWT, So please help me. I have on for loop n times loop; every loop sent the AsyncCallback to server and fetch the value. but I want to stop every loop until server response. for example

for (final String cardId : cardIds) {
    cmain.ivClient.getm(cardId, cardInfoKeys, new AsyncCallback<String[]>() {

        @Override
        public void onFailure(Throwable caught) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onSuccess(String[] result) {
            cardPar = result;
        }
    }
}

How to wait the loop for every time?

Upvotes: 0

Views: 237

Answers (1)

thst
thst

Reputation: 4602

Basically, you cannot really use the for loop in this case.

If you know, there will be, say, 3 calls, you can stack the async calls: In each onSuccess() you fire the next async call.

If you do not know how many there will be, you can recurse over the onSuccess call.

void callServer(final List<String>cardIds) {
    if(cardIds.isEmpty()) return;

    cmain.ivClient.getm(cardId, cardInfoKeys, new AsyncCallback<String[]>() {

        @Override
        public void onFailure(Throwable caught) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onSuccess(String[] result) {
            doImportantMatterWith( result );
            cardIds.remove(0);
            callServer(cardIds);
        }
    }
}

This is rather ugly, but will make sure, that the next call will only be fired, when the previous returned successful.

I suggest to not implement this async call chaining, but rather request all results from the server at once.

Upvotes: 2

Related Questions