2016-04-14 108 views
0

我正在使用FireBase,一種NOSQL雲數據存儲。當孩子(數據)被改變時,它可以自動更新我的JavaScript。不過,我有問題。如何處理ajax中的延遲

阿賈克斯的腳本:

var myDataRef = new Firebase('https://App_Name.firebaseio.com/session'); 
     myDataRef.on('child_added', function(snapshot) { 
     var message = snapshot.val(); 
     console.log("out of ajax: user"+ message.userId); 
     $.ajax({ 
      type: 'POST', 
      url: "showProfile.php", 
      data: {userId : message.userId}, 
      dataType: 'json', 
      success: function (data) { 
         console.log("inside ajax: user" + data.userId); 
        }, 
      error: function(e) { 
       console.log(e); 
      } 
     }); 
     }); 

的問題之一,它沒有運行同步。其次,它是無序的。 inside ajax:的順序僅取決於先到先得的順序。

結果在控制檯:

out of ajax: user1 
out of ajax: user2 
out of ajax: user3 
out of ajax: user4 
inside ajax: user3 
inside ajax: user2 
inside ajax: user4 
inside ajax: user1 

然而,我預期的結果是:

out of ajax: user1 
inside ajax: user1 
out of ajax: user2 
inside ajax: user2 
out of ajax: user3 
inside ajax: user3 
out of ajax: user4 
inside ajax: user4 

out of ajax: user1 
out of ajax: user2 
out of ajax: user3 
out of ajax: user4 
inside ajax: user1 
inside ajax: user2 
inside ajax: user3 
inside ajax: user4 
+0

你可以向'$ .ajax'提供'async:false'來使請求同步 – mani

+1

爲什麼你想讓它同步呢? –

+0

@mani我從它得到了另一個更大的問題...它會變得更加慢得多..btw,它同步。 –

回答