我正在node.js中制作一个非常简单的游戏。在我的TCP客户端中,我有一个异步函数,该函数返回一个Promise,当套接字收到信息后,Promise会解析,然后关闭。我的问题是:当我等待该函数时,程序会在解析以下示例之前继续运行:
async GetPlayers(player) {
return new Promise(resolve =>{
var net = require('net');
const client = new net.Socket();
client.connect({
port:this.port,
host:this.IpAdress
});
client.on('error',function(error){
console.log('Error : ' + error);
});
client.on('connect',function(){
client.write("sendPlayersToMePls: "+ JSON.stringify(player)+"\n");
var address = client.address();
var port = address.port;
var family = address.family;
var ipaddr = address.address;
});
client.on('data',function(data){
//
var data2 = data.toString();
if(data2.startsWith("hereAreYourPlayers: ")){
if(Config.Verbose)console.log("data = "+data2);
var players2 = data2.slice(20);
var obj = JSON.parse(players2);
that.FileSystem.allPlayers = obj.players;
that.FileSystem.TickCount= parseInt(obj.turnCount);
resolve(obj);
client.end();
}
});
}
//to call it i am using the following
async UpdateMapStatuses(player){
this.SetCurrentMap();
const players = await GetPlayers(player);
return new Promise(resolve => {
//the program starts exectuing this before "players" has been defined
//code that uses "players"
}
}
答案 0 :(得分:0)
尝试将client.on
回调转换为箭头函数,看看是否有帮助。例如:
async GetPlayers(player) {
return new Promise((resolve) =>{
var net = require('net');
const client = new net.Socket();
client.connect({
port:this.port,
host:this.IpAdress
});
client.on('error', (error) => {
console.log('Error : ' + error);
});
client.on('connect', () => {
client.write("sendPlayersToMePls: "+ JSON.stringify(player)+"\n");
var address = client.address();
var port = address.port;
var family = address.family;
var ipaddr = address.address;
});
client.on('data', (data) => {
//
var data2 = data.toString();
if(data2.startsWith("hereAreYourPlayers: ")){
if(Config.Verbose)console.log("data = "+data2);
var players2 = data2.slice(20);
var obj = JSON.parse(players2);
that.FileSystem.allPlayers = obj.players;
that.FileSystem.TickCount= parseInt(obj.turnCount);
resolve(obj);
client.end();
}