メッセージ リストを保持する変数を持つ JavaScript コードがあり、これは以下messageList
の関数で更新できます。updateMessageList()
var messageList=[]; //contains list of messages
function updateMessageList(id, lastUpdate); //updates messageList item for given id
//at some point while running
mesasgeList=[
{id:1, lastUpdate:1371650818000},
{id:2, lastUpdate:1371650821000},
.....
]
2 つの異なるソースが同じ項目updateMessageList()
に対して同時に関数を呼び出すとどうなりますか。messageList
メッセージの 1 つの更新がid:1
クライアント (現在のユーザーがメッセージを更新している) から来て、別のメッセージがサーバーから来ているとしますid:1
(別のユーザーがメッセージを更新します)。その後、両者messageList[0].lastUpdate
は同時にプロパティへのアクセスと変更を試みます。
ソース 1: クライアントがメッセージ フォーム送信イベントを更新すると、関数がトリガーされます。handleReply()
function handleReply(event) {
.....
var id=event.currentTarget.find('input[name="id"]').val();
//form has an hidden input for id of the message
var d = new Date();
updateMessageList(id, d.getTime());
.....
}
ソース 2: JS はサーバーに対して AJAX 呼び出しを行い、更新があるかどうかを確認updateMessages()
し、代わりに関数を実行します。
//server sends following JSON data:{id:1, lastUpdate:1371650823269}
function updateMessages(data) {
.....
updateMessageList(data.id, data.lastUpdate);
.....
}
updateMessageList()
関数は両方とものlastUpdate
プロパティを変更しようとしますmessageList[0]
。
では、プログラミング中にこの種の状況を考える必要がありますか、それとも JavaScript でこれらを処理できますか?