Tarlen
Tarlen

Reputation: 3797

Perform action after parallel, asynchronous calls have completed on client

In my client code, I fire multiple asynchronous requests parallel, and I want to call a method, after each has completed.

This is my code

_handlePostSubmit() {
    this._clearFailedPostingGraphs();

    _.forEach(this.state.selectedGraphs, (graph) => {
      this.__createPosting(graph.graphType, graph._id, this.state.content, (error, result) => {
        if (error) {
          this._pushFailedPostingGraph(graph, error);
        } else {
          this._pushSuccesfulPostingGraph(graph);
        }
      }, this);
    }, this);
    this.props.onFetchPostings(); <------- should be called when all the 'createPosting' have completed
  },

How can I achieve this?

Upvotes: 1

Views: 43

Answers (1)

al .js
al .js

Reputation: 206

and I want to call a method, after each has completed.

I assume you meant after all requests have completed.

If so, count the callbacks from the async requests, and if they equal the number of async requests, do your next thing:

_handlePostSubmit() {
  this._clearFailedPostingGraphs();

  var expectedCallbacks = this.state.selectedGraphs.length;
  var callbackCount = 0;

  _.forEach(this.state.selectedGraphs, (graph) => {
    this.__createPosting(graph.graphType, graph._id, this.state.content, (error, result) => {
      if (error) {
        this._pushFailedPostingGraph(graph, error);
      } else {
        this._pushSuccesfulPostingGraph(graph);
      }

      callbackCount++;

      // this is what I moved -- the method you want to call after everything's done
      if (callbackCount >= expectedCallbacks) {
        this.props.onFetchPostings();
      }
    }, this);
  }, this);
},

jQuery's .when() and Underscore's after() will do this without you having to manually set up a counter variable.

Upvotes: 2

Related Questions