私はまだステップの実行方法を理解するのに苦労しています。mysqlの挿入前にforeachを実行しています
基本的に私は、foreachのコンピューティングの色をしています、通常のforeachの コードと、それをデータベースに挿入します。
var mysql = require("mysql"),
namer = require('color-namer'),
async = require('async');
var connection = mysql.createConnection({
multipleStatements: true,
host : 'localhost',
user : 'root',
password : 'root',
database : 'xxxx'});
connection.connect();
connection.query(
`SELECT color from sg_fashion_colors limit 10`,
function(err, results, fields) {
results.forEach(function(elem){
var currentHex = elem['color'],
currentColor = namer(currentHex);
console.log(currentHex);
connection.query(
`INSERT INTO name_color_pat_test (hex, basic) VALUES (?,?);`,
[currentHex,currentColor['basic'][0]['name']] ,
function(err,data){
console.log("insert");
}
);
});
}
);
代わりの
color
insert
color
insert
を行うことが
color
color
insert
insert
を行います
私はちょうどなぜそれが最初になるのかについてのメカニズムを理解していません各色の上に挿入し、foreachを挿入します。
var colors = ['blue', 'red', 'green'];
colors.forEach(function(color) {
console.log('before setTimeout', color);
setTimeout(function() {
console.log('after setTimeout', color);
}, 0);
});
私はクロームコンソールでそれをしようとした場合:私は、非同期
connection.query(
`SELECT color from sg_fashion_colors limit 10`,
function(err, results, fields) {
async.eachSeries(results, function (elem, seriesCallback) {
var currentHex = elem['color'],
currentColor = namer(currentHex);
console.log(currentHex);
connection.query(`INSERT INTO name_color_pat_test (hex, basic) VALUES (?,?);`, // insert the SKU inside a database with their primary color
[currentHex,currentColor['basic'][0]['name']] ,
function(err, results, fields) {
if (err) throw err;
console.log("insert");
seriesCallback(null);
});
}, function(responsetoendofloop){
console.log("everything has run");
});
}
);
'connection.query'は非同期です。したがって、forEachループが終了した後にのみコールバック関数が呼び出されることが保証されています**すべて**反復 –