我正在尝试使用猫鼬将一些数据保存到我的收藏中。
//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个值都推入数据库?
最佳答案
我的本地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
吗?确实可以在控制台连接相同的索引。关于javascript - 如何使async.each等待.save()完成?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47705969/