我想在async.series块的第三个函数中调用self.setState( { date_data: tour_dates});
。所以我有一个嵌套的函数,似乎甚至在每个块上使用.bind(this)似乎都没有解决我的问题。我错过了什么?我应该如何改变我的编码风格以避免这样的问题?
var mysql = require('mysql');
var async = require('async');
var self = this;
var moment = require('moment');
class ArtistTable extends React.Component {
constructor(props, context) {
super(props, context);
this.getArtistData = this.getArtistData.bind(this);
this.state = {
open: false,
date_data: [],
};
}
getArtistData (artistName) {
var artist_id = -1;
var tour_id = -1;
var tour_dates = new Array();
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'anand2'
});
connection.connect(function(err) {
if (err) {
console.error('MYSQL Error Connecting!' + err.stack);
return;
}
console.log('MYSQL ArtistTable connected as ' + connection.threadId);
});
async.series([
function(callback){
connection.query("SELECT * FROM artist WHERE name = '" +artistName+"'" , function(err, rows){
artist_id = rows[0].id;
callback();
});
}, function(callback){
//finde tour ID
connection.query("SELECT * FROM tour WHERE artist = " + artist_id , function(err, rows){
console.log("SELECT * FROM tour WHERE artist = " + artist_id ) //Todo: neue erstellen
console.log(rows.length)
tour_id = rows[0].id;
console.log("Tour ID is " + tour_id)
callback();
});
}, function(callback){
connection.query("SELECT dtime,location FROM tour_date WHERE tour="+ tour_id + " AND dtime >= CurDate() ORDER BY dtime ASC" , function(err, rows){
if (rows.length > 0) {
for (var i = 0; i < rows.length; i++) {
tour_dates.push({date: rows[i].dtime, location: rows[i].location });
}
console.log("Number of dates: " + tour_dates.length)
self.setState( { date_data: tour_dates});
}
}.bind(this));
}
]);
}
}
另外,请忽略“self = this”,这是一个测试,我确实试过了。
答案 0 :(得分:0)
你需要在async.series之前将self = this放在getArtistData中。