Nodejs:Sequelize和Promises - 没有像预期的那样真正地工作

时间:2015-10-26 17:03:03

标签: node.js promise sequelize.js

正当我认为我理解了Promises时,一些代码向我显示了相反的情况。 我有一个数组,其中包含来自数据库查询的(大)结果(使用Sequelize)。

我想要做的是循环结果,对于每一行,我想将一些数据插入到另一个数据库表中。当最后一次插入完成后,我想返回一个promise,这样我的(sync)命令链就可以继续了。

// above ^ is code for retrieving results from db
.then(function (results) {
    return Promise.map(results, function(row) {
        log.info('Handle ' + row.file);

        // Images is a sequelize model defined above
        return Images.create({
            id: row.image_id,
            file: row.image_original_source
        }).then(function() {
            log.info('DB insert for ' + row.id);
        }).catch(function(err) {
            log.error(err);
        });
    });
})
.then(function (results) {
// continue the chain when all Images are made

我希望一旦循环开始,Images.create就会开始插入数据库。

相反,代码会等待所有结果循环,然后才开始向数据库插入内容。当结果有10k +元素时,很容易看到。输出所有“Handle”日志记录,然后才开始输出“DB insert for”。

感谢您的任何意见。

0 个答案:

没有答案