简体   繁体   中英

How to make the async.each wait for the .save() to be completed?

I am trying to save some data into my collection, using 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(); } }); 

The problem is that it pushes me only the value corresponding to the last index.(out of 133 values). I have the ID unique, so that is why there is only one value saved in the data base. I placed a console.log into the addChampion function and for 133 times I see the same value. Add champion snippet added below:

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

How I solve this problem, in order to have all 133 values pushed into the DB?

Async job with my local 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 } ]

Simple case with not a really async job :

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 }

Would you check your newChampion before passing into the addChampion function? It's really wired you can the same index at console in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM