如何让async.each等待.save()完成?

时间:2017-12-08 00:26:49

标签: javascript node.js mongoose

我正在尝试使用mongoose将一些数据保存到我的集合中。

//tried with async each
async.each(indexes, function(index, callback) {
            newChampion.ID = champions[index].id;
            newChampion.Key = champions[index].key;
            newChampion.Name = champions[index].name;
            newChampion.Title = champions[index].title;
            Champion.addChampion(newChampion, function(err) {
                if (err) {
                    console.log(err.message);
                    callback();
                } else {
                    callback();
                }
});

问题是它只推送了与最后一个索引相对应的值。(在133个值中)。我有唯一的ID,这就是数据库中只保存一个值的原因。我将console.log放入addChampion函数中并且133次看到相同的值。添加以下添加的冠军摘录:

module.exports.addChampion = function(newChampion, callback) {
    newChampion.save(callback);
}

我如何解决这个问题,以便将所有133个值推入数据库?

1 个答案:

答案 0 :(得分:0)

使用我的本地mysql进行异步作业:

let async = require('async');
let mysql = require('mysql');

var conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'xxxxx',
    database: 'xxxxx',
    port: 3306
});

var sqls = [
    'select id from record where id = 1',
    'select id from record where id = 2',
    'select id from record where id = 3',
    'select id from record where id = 4',
    'select id from record where id = 5'
];

async.each(sqls, function(sql, callback) {
    console.log(sql);
    conn.query(sql, function (err, res) {
        console.log(res);
    });
});
### output ###
select id from record where id = 1
select id from record where id = 2
select id from record where id = 3
select id from record where id = 4
select id from record where id = 5
[ RowDataPacket { id: 1 } ]
[ RowDataPacket { id: 2 } ]
[ RowDataPacket { id: 3 } ]
[ RowDataPacket { id: 4 } ]
[ RowDataPacket { id: 5 } ]

没有真正异步工作的简单案例:

let async = require('async');

let addChampion = function(newChampion, callback) {
    console.log(newChampion)
}

indexes = [1, 2, 3];
async.each(indexes, function(index, callback) {
    newChampion = {};
    newChampion.ID = index;
    addChampion(newChampion, function(err) {
        if (err) {
            console.log(err.message);
        }
    })
});

### output ###
{ ID: 1 }
{ ID: 2 }
{ ID: 3 }

在进入newChampion功能之前,您会检查addChampion吗?它真的很有线,你可以在控制台上使用相同的索引。

相关问题