所以我想做的是创建一个函数,使用mysql(不在乎如何,但是我找到了一个npm,所以现在就使用它。)从数据库中获取信息,然后提供我的json用它。只要console.log()在正确的位置,它就可以正常工作,但是我必须返回它,所以我必须将其进一步向下移动。但是当我这样做时,它将不会显示在我需要的其他文件中。
我有两个基本相同的剧本,一个只适合另一个派别。 -所以我只会显示一个,就好像我为其中一个找到了解决方案一样,我对两个都有解决方案。
get_ally_online_players: function (guild) {
con.query("SELECT * FROM user_dbs WHERE guild='"+ guild +"'", function (err, result, fields) {
var con2 = mysql.createConnection({
host: result[0].host,
user: result[0].username,
password: result[0].password,
database: result[0].database
})
con2.connect()
con2.query("SELECT * FROM characters WHERE online='1' AND race=1 OR race=3 OR race=4 OR race=7 OR race=11", function (err, result, fields) {
allycount = 0
console.dir(result)
result.forEach(function(result) {
allycount = allycount+1
})
return allycount
});
con2.end()
});
}
在这里我尝试拥有它:
if(recieved.content === "!status")
{
var horde_players
var ally_players
horde_players == guilddb.get_horde_online_players("585919060722712670")
ally_players == guilddb.get_ally_online_players("585919060722712670")
console.log(guilddb.test())
//console.log(ally_players)
recieved.channel.send(ally_players + " : " + horde_players)
}
我已经尝试了很多事情...我还读到您必须使用回调函数,因为它显然太快了,就像以前无法查询一样... 不过,我想远离回调,因为在脚本中包含它似乎很麻烦。但是,如果绝对必要,那就这样吧。它返回“未定义” btw。我也曾尝试使用Promise并放置setTimeout函数等。
答案 0 :(得分:1)
首先,对我的英语感到抱歉。
实际上您犯了一些错误。
您在犯错误的情况下将值分配给 horde_players 和 ally_players 值
<div class="searching-result" data-id="somehashvalue" abc="xyz"></div>
使用(==),您正在比较值,而不是设置。
现在让我们讨论异步操作。
我准备了一个例子。就像您的情况一样,您试图运行两个可能在不同时间完成的异步操作,但是在运行其他操作之前您需要将它们都完成。尝试运行它:
if (recieved.content === "!status") {
var horde_players
var ally_players
horde_players = guilddb.get_horde_online_players("585919060722712670")
ally_players = guilddb.get_ally_online_players("585919060722712670")
console.log(guilddb.test())
//console.log(ally_players)
recieved.channel.send(ally_players + " : " + horde_players)
}
完成的结果是在完成两个异步操作之前运行的。错误...
使用回调,我们需要嵌套函数(如果您必须执行更多异步操作,则可能会导致回调地狱)
function async1(id, callback) {
setTimeout(function() {
callback('The user with ' + id + ' is called Sergio');
}, 6000);
}
function async2(id, callback) {
setTimeout(function() {
callback('The user with ' + id + ' is called Jack');
}, 2000);
}
var result1;
var result2;
async1(1, function(result) {
result1 = result;
});
async2(2, function(result) {
result2 = result;
});
console.log('Finished result: ' + result1 + result2); // Finished result: undefined undefined
对于您而言,这就是我的解决方案。也许我会改善更多的功能,例如使用const-let和ES6功能(异步等待,箭头功能...),传递数据库连接器引发的参数崩溃……但也许现在更容易理解
function async1(id, callback) {
setTimeout(function() {
callback('The user with ' + id + ' is called Sergio');
}, 6000);
}
function async2(id, callback) {
setTimeout(function() {
callback('The user with ' + id + ' is called Jack');
}, 2000);
}
var result1;
var result2;
async1(1, function(result) {
result1 = result;
async2(2, function(result) {
result2 = result;
console.log('Finished result: ' + result1 + result2); // 'Finished result: The user with 1 is called SergioThe user with 2 is called Jack
});
});
希望有帮助。
答案 1 :(得分:0)
您的查询是异步的,因此该函数将在查询完成之前隐式返回 undefined 。
因此,您将需要使用回调或Promise。
您可以使用如下回调:
public class Kompjuterike extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kompjuterike);
displayUpload();
editPdfName = (EditText) findViewById(R.id.txtuploadfile);
pdfupload = (ImageView) findViewById(R.id.pdfuploadimg);
imgupload = (ImageView) findViewById(R.id.imguploadimg);
storageReference = FirebaseStorage.getInstance().getReference();
databaseReference =
FirebaseDatabase.getInstance().getReference(databasepath);
}
private void selectPDFFile() {
Intent intent=new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"select pdf file"),1);
}
private void selectIMGFile() {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"select img file"),1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1 && resultCode==RESULT_OK && data!=null && data.getData()!=null){
uploadFile(data.getData());
}
}
private void uploadFile(Uri data) {
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setTitle("Uploading file...");
progressDialog.show();
final StorageReference reference=storageReference.child(databasepath+"/"+System.currentTimeMillis());
reference.putFile(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(Kompjuterike.this, "Upload successful!", Toast.LENGTH_LONG).show();
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String url = uri.toString();
Upload upload = new Upload(editPdfName.getText().toString(), url);
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
Toast.makeText(Kompjuterike.this, "File Uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0*taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount();
progressDialog.setMessage("Uploaded: "+(int)progress+"%");
}
});
}
private void displayUpload(){
uploadList = new ArrayList<>();
listView = (ListView) findViewById(R.id.listView1);
//adding a clicklistener on listview
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//getting the upload
Upload upload = uploadList.get(i);
//Opening the upload file in browser using the upload url
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(upload.getUrl()));
startActivity(intent);
}
});
//getting the database reference
databaseReference = FirebaseDatabase.getInstance().getReference(databasepath);
//retrieving upload data from firebase database
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
uploadList.add(upload);
}
String[] uploads = new String[uploadList.size()];
for (int i = 0; i < uploads.length; i++) {
uploads[i] = uploadList.get(i).getName();
}
//displaying it to list
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.listview_color,R.id.list_content, uploads);
listView.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
...然后将回调函数传递给// Accept a callback function as an argument
get_ally_online_players: function (guild, callback) {
con.query("SELECT * FROM user_dbs WHERE guild='"+ guild +"'", function (err, result, fields) {
var con2 = mysql.createConnection({
host: result[0].host,
user: result[0].username,
password: result[0].password,
database: result[0].database
})
con2.connect()
con2.query("SELECT * FROM characters WHERE online='1' AND race=1 OR race=3 OR race=4 OR race=7 OR race=11", function (err, result, fields) {
allycount = 0
console.dir(result)
result.forEach(function(result) {
allycount = allycount+1
})
// Pass the result to the callback function
callback(allycount)
})
con2.end()
})
}
,该回调函数将在准备就绪时接收数据:
get_ally_online_players
我希望这会有所帮助。