2017-12-29 33 views
-3

를 사용하여 약속을 실행 해달라고. 노드 쪽에서 게임 인스턴스를 만들면 타일과 숨겨진 이미지 (두 이미지가 모두 api에서 나옵니다)가 표시됩니다. 이것은 액시오를 사용하기 때문에 문제는 생성 된 게임이 액시스를 실행하기 전에 클라이언트에 반환된다는 것입니다. 그래서 클라이언트는 이미지없이 게임을 얻습니다.비동기 Axios의 (나는 클라이언트와 서버가 통신 할 수 <code>vue-sockets.io</code>를 사용하고) 내가 클라이언트 측에서 <em>VUE</em> 및 <em>nojejs 게임 서버로</em>를 사용하여 멀티 플레이어 게임을 개발하고 있어요 NODEJS

createGame(playerName, socketID, boardSize) { 
    this.contadorID = this.contadorID+1; 

     var game = new MemoryGame(this.contadorID, playerName, boardSize); 

     new Promise(function(resolve, reject) { 
      console.log("a"); 
      game.getTiles().then(response=>{ 
       console.log("getTiles"); 
     game.tiles = game.getRandomNPieces(response.data.data, game.board.length/2); 
       console.log(game.tiles); 
     }).catch(function (error) { 
     console.log(error); 
     }); 
      console.log('=>' + game.tiles); 
     }).then(function(result) { // (***) 
      console.log("b"); 
      game.getHidden().then(response=>{ 
     game.hidden = game.getRandomHidden(response.data.data); 
     }).catch(function (error) { 
     console.log(error); 
     }); 
     }).catch(function (error) { 
      console.log(error); 
     }); 
    game.player1SocketID = socketID; 
    this.games.set(game.gameID, game); 
    return game; 
} 

Print with logs

이 프로그램은 결코 두 번째 Axios의 호출에 도달하지 않습니다. gameList 로그는 사용자에게 반환되는 게임에서 가져옵니다. (게임이 로비에 이미 타일이) 클라이언트 2 Game instance in client 1 (who created the game)

게임 인스턴스 : createGame() 이후 Game instance in client 2 (the game is in lobby and already have the tiles)

+1

가 효율적으로 여러분을 도와 : 당신이처럼 사용하는 방식을 변경해야하므로

createGame(playerName, socketID, boardSize) { this.contadorID = this.contadorID+1; var game = new MemoryGame(this.contadorID, playerName, boardSize); console.log("a"); return game.getTiles().then(response=> { console.log("getTiles"); game.tiles = game.getRandomNPieces(response.data.data, game.board.length/2); console.log(game.tiles); console.log('=>' + game.tiles); console.log("b"); // return nested promise so it chains into main promise chain return game.getHidden().then(response=>{ game.hidden = game.getRandomHidden(response.data.data); }); }).then(() => { // finish initializing game object and // make it be the resolved value of the returned promise game.player1SocketID = socketID; this.games.set(game.gameID, game); return game; }).catch(function (error) { // log error and rethrow so promise stays rejected // this will log for any of our rejected promises since they are chained console.log(error); throw error; }); } 

그리고,이 createGame() 변경이 약속을 반환 : 여기에 있음을 구조화하는 방법 중 하나입니다 코드의 관련 부분을 텍스트로 붙여 넣어 코드로 형식화해야합니다. 그런 다음 해당 부분을 복사/붙여 넣기하고 수정할 수 있습니다. 코드는 이미지에 대한 외부 링크로만 사용할 수 없어야합니다. 텍스트로 질문에 붙여 넣어야합니다. 이것들은 스택 오버 플로우의 규칙/가이드 라인입니다. 코드에는 여러 가지 문제가 있지만 이미지 수정 코드를 수동으로 다시 입력하지 않아도됩니다. – jfriend00

+0

@ jfriend00 귀하의 조언에 감사드립니다! 나는 내 코드를 지나칠거야! – BLDD

+0

비동기 작업을 수행하면서이 코드가 수행해야 할 작업을 확신 할 수 없지만 아직 조작되지 않은'game' 객체를 동 기적으로 반환하려고 시도하고 있지만 첫 번째 핵심 문제는 ' 새로운 Promise()'를 사용하지만 그 약속을 해결하거나 거부하기 위해 결코'resolve()'또는'reject()'를 호출하지 마십시오. 당신이 보여주는 것은 약속의 안티 패턴입니다. 또 다른 약속에서'getTiles()'의 기존 약속을 래핑 할 필요가 없다. 당신은 단지 그것이 반환하는 약속을 사용할 수 있습니다. 이 코드에는 많은 문제점이 있습니다. 그것의 목적이 무엇인지 확실하지 않습니다. – jfriend00

답변

1

가 나타납니다 (게임을 만든) 클라이언트 1

게임 인스턴스 일부 비동기 작업을 사용하여 게임을 올바르게 초기화하면 createGame()에서 완료된 게임 객체를 동 기적으로 반환 할 수 없습니다. 이미 살펴본 것처럼 createGame()은 비동기 작업이 완료되기 전에 게임 개체를 반환합니다. 따라서, 당신이해야 할 일은 해결 된 가치가 게임 객체 인 약속을 반환해야하고 모든 비동기 작업을 적절하게 연결하여 게임 객체가 모두 완료되면 주요 약속이 해결되도록해야한다는 것입니다. 위해

someObj.createGame(...).then(game => { 
    // game object is ready to use here 
}).catch(err => { 
    // error creating game object 
}); 
+0

내 문제가 해결되었습니다! 고맙습니다! – BLDD

+0

응답 허용 및 상향 고려해보기 @BLDD –