2016-04-14 144 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,它同步。 –

回答