【问题标题】:How do I make for loop wait for db promise to finish before it continues to next iteration?在继续下一次迭代之前,如何让 for 循环等待 db promise 完成?
【发布时间】:2016-10-05 22:24:27
【问题描述】:

我目前使用 node.js sequalize 从数据库中提取数据,在前端我使用 ajax 请求。所以我发送带有 json 对象的 ajax 请求来编辑数据库。但是,当我尝试编辑数据库时,foor 循环不会等待承诺完成,然后再进行下一次迭代。我尝试将承诺发送到数组并使用 Bluebird 函数 Promise.each 但承诺在发送到数组之前就已执行。我该怎么做才能在当前承诺完成之前暂停 for 循环?

for(var i=0; i<recordsJSON.length; i++)
{
    var recordJSON = recordsJSON[i];

    Record.nullPayeeId(recordJSON.id).then(function()
    {
        return Record.getOneRecord(recordJSON.id);
    })
    .then(function(record)
    {
        var virtualPayeeId = record.virtualPayeeId;
        return VirtualPayee.deletePayee(virtualPayeeId);
    })
    .then(function()
    {
        var category = parseInt(recordsJSON[i].category);
        var subcategory = parseInt(recordsJSON[i].subcategory);

        return VirtualPayee.insertPayee({
            payee: recordJSON.payee,
            description: recordJSON.description,
            categoryId:category,
            subcategoryId:subcategory
        })
    })
}

【问题讨论】:

    标签: javascript ajax


    【解决方案1】:

    既然你说的是Bluebird,你可以用Promise.mapSeries()来帮你序列化东西:

    Promise.mapSeries(recordsJSON, function(recordJSON) {
        return Record.nullPayeeId(recordJSON.id).then(function () {
            return Record.getOneRecord(recordJSON.id);
        }).then(function(record) {
            var virtualPayeeId = record.virtualPayeeId;
            return VirtualPayee.deletePayee(virtualPayeeId);
        }).then(function() {
            var category = parseInt(recordJSON.category);
            var subcategory = parseInt(recordsSON.subcategory);
    
            return VirtualPayee.insertPayee({
                payee: recordJSON.payee,
                description: recordJSON.description,
                categoryId: category,
                subcategoryId: subcategory
            });
        });
    }).then(function (results) {
        // results here in oder
    }).catch(function (err) {
        // error here
    });
    

    如果您想手动序列化它们,那么您可能希望在您的 Promise 中使用 .reduce() 模式。您可以在此处阅读有关该模式的信息:

    JavaScript: Perform a chain of promises synchronously

    How to synchronize a sequence of promises?

    Can Promise load multi urls in order?

    【讨论】:

    • 非常感谢您。这对我帮助很大。我认为 mapSeries 只映射了承诺。如果不是你,我永远不会看到。再次感谢您!
    猜你喜欢
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多