2016-11-07 52 views
-3

我在我的AJAX處理的each()循環做推到我temp陣,但最終我還是得到一個空數組。這很奇怪,我記得我曾經在each()上使用諾言,所以它沒有問題。

var temp = []; 
$.ajax({ 
    type: 'GET', 
    url: '/endpoint', 
    success: function(data) { 
     $(data).each(function() { 
      //do some stuff 
      console.log(something); // working 
      temp.push(something); 
    }).promise().done(function() { 
     console.log(temp); // still empty array?! 
    }); 
}); 

更新:這裏的人是如何做到了https://stackoverflow.com/a/8941358/7095330

+1

還有的[文件]中的任何內容(http://api.jquery.com/jquery。每個/)表明'.each'返回一個承諾 – Liam

+0

也許這不是一個傻瓜,在OP似乎做奇怪的事情與同步循環? – adeneo

+0

讓我困惑的是大括號不匹配。有太多的收盤'}' – Liam

回答

2

減少你的腳本,你的問題是問,一切似乎是工作的罰款。希望這將有助於你發現,你的問題是,別的地方在你的代碼:

var temp = []; 
 
var data = [1,2,3,4,5,6,7,8]; 
 

 
$(data) 
 
    .each(function(thing) { 
 
     //do some stuff 
 
     console.log(thing); // working 
 
     temp.push(thing); 
 
    }) 
 
    .promise() 
 
    .done(function() { 
 
     console.log(temp); // still empty array?! 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

然而promise().done()是很奇怪的;我看不出爲什麼你需要那裏。

聽起來像是map,那就是你有一個輸入數組的情況下,你想改變它的內容。

var data = [1,2,3,4,5,6,7,8] 
 

 
var changedData = data.map(function (datum) { 
 
    // do stuff 
 
    return 'did stuff to ' + datum; 
 
}); 
 

 
console.log(changedData)

除非你試圖做的是下面的,這仍然有效。 PEBKAC錯誤或許?

var temp = []; 
 
$.ajax({ 
 
    type: 'GET', 
 
    url: 'https://google.com/', 
 
    // replaced success: with error:, for example's sake 
 
    error: function(data) { 
 
     $(data).each(function() { 
 
      //do some stuff 
 
      console.log('something'); 
 
      temp.push('something'); 
 
     }).promise().done(function() { 
 
      console.log('each done', temp); 
 
     }); 
 
    }, 
 
    done: function() { 
 
     console.log('ajax done:', temp); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

我不相信任何他在'成功'回調中做的任何事情都是異步的。在這種情況下將'.each'包裝成承諾與使用純粹的同步替代無差別。除非我現在很胖,並且缺少明顯的東西......在這種情況下,我很樂意知道。 – tmslnz

+0

在他嘗試記錄'temp'之前執行的操作是同步的,因爲它都發生在'success'回調中。 – tmslnz

+0

也許你的權利... – Liam

1

你忘了一個支架}

var temp = []; 
$.ajax({ 
    type: 'GET', 
    url: '', 
    success: function(data) { 
     $(data).each(function() { 
      //do some stuff 
      console.log('something'); // working 
      temp.push('something'); 
    }).promise().done(function() { 
     console.log(temp); // still empty array?! 
    }); 
}}); 

看到https://jsfiddle.net/gw10un58/