【问题标题】:Maintaining order of http requests within a for loop in javascript在javascript的for循环中维护http请求的顺序
【发布时间】:2015-07-10 11:48:26
【问题描述】:

我正在尝试使用 node.js express 和 mongoose(MEAN 堆栈)在 MongoDB 中保存一组对象。但是,当我在前端为数组中的每个项目发出 http 发布请求时,它们不会按该顺序显示在后端。这是我在前端的内容:

$scope.postThenPost = function() {
    $http.post('/collection', $scope.doc).success(function(data){
        for (var i = 0; i<$scope.array.length; i++) {
            var req_obj = { thing: $scope.array[i] };
            $http.post('/collection2', req_obj);
        };
    };
};

在后端,express 运行这个以发布到 /collection2:

exports.create = function(req, res) {
    var q = new q(req.body.thing);
    q.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(q);
        };
    });
};

我可以做些什么来确保数组按顺序进入数据库吗?提前致谢

【问题讨论】:

  • $http.post 默认是异步的。我建议您将整个$scope.array 发布到/collection2,然后在后端循环遍历数组。

标签: javascript node.js mongodb loops mongoose


【解决方案1】:

当您准备好要发送的所有数据时,发送 $scope.array.length 数量的 HTTP 请求是很浪费的。

只需将整个数组发布到您的后端,然后您可以使用async 之类的东西将它们保存在后端的循环中以保证顺序。

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多