【问题标题】:JavaScript: wait for every asynchronous call finished [duplicate]JavaScript:等待每个异步调用完成[重复]
【发布时间】:2014-10-14 20:32:47
【问题描述】:

我正在尝试从多个来源加载数据,并且希望仅在加载所有数据后继续处理。这是我的代码:

var tables = [];
$http
    .get('/tables')
    .then(function (response) {
        _.each(response.data, function (table) {
            tables.push(table);
        });
    })
    // get detail data
    .then(function () {
        _.each(tables, function (table) {
            $http.get('/tables/' + table)
                .success(function (data) {
                    process(data);
                });
        });
    })
    .then(function () {
        // after everything loaded
        // run this function
    });

感谢您的帮助!

【问题讨论】:

    标签: javascript underscore.js promise angular-promise


    【解决方案1】:

    您应该使用以下内容:

    .then(function () {
        return $q.all(_.map(tables, function (table) {
            return $http.get('/tables/' + table)
            .success(process);
        });
    })
    

    与您问题的主要部分无关,但请注意,如果您只是要将参数传递给 process(),则无需为 .success 定义全新的匿名函数。

    另请参阅:$q promise with Underscore _each

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 2019-10-30
      • 1970-01-01
      相关资源
      最近更新 更多