1

I need to call the same asynchronous function multiple times but not till one call is finished (i.e. when the callback function is executed). So my code looks like this:

syncFunc(a, function() {
    syncFunc(b, function() {
        syncFunc(c, function() {
            syncFunc(.....)
        });
    });
});

Is it now possible to shorten this somehow? My first idea was using a for loop, like:

syncParams = [a, b, c, ...];
for(var i = 0;; i++) {
    syncFunc(syncParams[i], function() {
        if(i < syncParams.length - 1) {
            alert('finished');
            break;
        } else {
            continue;
        }
    }
}

But obviously this does not work as there's no connection for the continue and break to the loop. My other idea was using an interval to check every second if one async call is finished and then call the next one with the next parameter, but this seems too complicated. Is there any easy way without using some library?

EDIT: Because nobody unterstood the library issue: I am developing a PhoneGap mobile app and with the IDE I'm currently working with it is not that pleasent to include a third party library. Also I was just curious how this would work.

2
  • 1
    possible duplicate of How to synch JavaScript callbacks?; it's about Ajax, but the answer should apply here as well. Commented May 14, 2013 at 13:38
  • 2
    The ideal way to solve this would be a promise maker. If you don't want to use a library for that (which I could not understand), you need to write one for yourself. Commented May 14, 2013 at 13:39

1 Answer 1

0

I see you want to call the function with a different argument each time. Then async.forEachSeries would be most appropriate.

If you want to call the function with the same argument every time, async.whilst would work well. https://github.com/caolan/async/#whilsttest-fn-callback

Mentioned by @Jack, this question has a good answer for doing it yourself: How to synch JavaScript callbacks?

Sign up to request clarification or add additional context in comments.

3 Comments

That's cheating, because it uses "some library" ;)
Oh wait, I miss-read the question. I thought it said: an easy way with using some library. Whatever. I don't understand people's problems with using libraries. Or steal a piece of the code, if you really can't afford to load it in full.
I agree, no need to reinvent each wheel yourself :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.