繁体   English   中英

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

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

我正在尝试使用猫鼬将一些数据保存到我的收藏中。

 //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功能? 确实可以在控制台连接相同的索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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