gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:39 25 4
gpt4 key购买 nike

我正在尝试使用 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 个值插入数据库?

最佳答案

与本地 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 }

在传递给 addChampion 函数之前,您会检查您的 newChampion 吗?它确实是连线的,您可以在控制台中使用相同的索引。

关于javascript - 如何让 async.each 等待 .save() 完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47705969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com