我目前正在使用node.js sequalize从数据库中提取数据,而在前端,我正在使用ajax请求。所以我要发送一个带有json对象的ajax请求来编辑数据库。但是,当我尝试编辑数据库时,foor循环不会等到承诺完成后再进行下一次迭代。我试图将promise发送到数组,并使用Bluebird函数Promise.each,但是promise在被发送到数组之前就已执行。我该怎么办才能在当前的Promise完成之前暂停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
        })
    })
}

最佳答案

由于您是指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
});


如果要手动序列化它们,则可能需要将.reduce()模式用于您的promises。您可以在此处阅读有关该模式的信息:

JavaScript: Perform a chain of promises synchronously

How to synchronize a sequence of promises?

Can Promise load multi urls in order?

07-24 09:46
查看更多