F
F
Fragman2019-08-09 03:04:02
Node.js
Fragman, 2019-08-09 03:04:02

How to fix concurrent code execution?

There is such a code that is executed immediately after the player connects. Faced a problem that if players connect at the same time, the startGame function does not work. The statuses of both players do not have time to update. What to do?

if(p1.id == userid)
  p1.status = 'connected';
else
  p2.status = 'connected';
if(status == 'created' && p1.status == 'connected' && p2.status == 'connected')
  startGame();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Neverov, 2019-08-09
@TTATPuOT

It's hard to tell from the code you provided. Most likely, the problem is that you did not take asynchrony into account.
Great video on the topic: https://youtu.be/8cV4ZvHXQL4
And this is an article on how to use asynchrony in practice: https://medium.com/devschacht/ire-aderinokun-async...
Well, there is a CodeDojo channel on YouTube - Highly recommended for understanding the basics of JavaScript.

B
Boris Korobkov, 2019-08-09
@BorisKorobkov

Subscribe (for example, using Promise) to change status, p1.status, p2.status.
On any of the above events, perform checks and run startGame.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question