Javascript - synchronizing after asynchronous calls

前端 未结 6 1628
北恋
北恋 2021-02-04 02:08

I have a Javascript object that requires 2 calls out to an external server to build its contents and do anything meaningful. The object is built such that instantiating an inst

6条回答
  •  长发绾君心
    2021-02-04 02:55

    I can add that Underscore.js has a nice little helper for this:

    Creates a version of the function that will only be run after first being called count times. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.

    _.after(count, function)
    

    The code for _after (as-of version 1.5.0):

    _.after = function(times, func) {
      return function() {
        if (--times < 1) {
          return func.apply(this, arguments);
        }
      };
    };
    

    The license info (as-of version 1.5.0)

提交回复
热议问题