Coffeescription不遍历整个对象

Coffeescript not iterating through entire object

本文关键字:对象 遍历 Coffeescription      更新时间:2023-09-26

我正试图创建一个函数,通过ajax请求数据库中国家ID的信息,因为这就是我查询的address表中数据的表示方式。也就是说,在address表中,表示的是国家的id,而不是国家名称,实际的国家名称在我查询的另一个表中。

在我发送ajax请求后,我会创建一个地址字符串。然而,它只是更新对象的最后一个值,而不是所有值。这是我的咖啡脚本:

requests = Array()
for key, val of {'Correspondence_Country__c':data['Correspondence_Country__c'], 'Country_of_Residence__c': data['Country_of_Residence__c']}
        console.log(key)
        console.log(val)
        requests.push($.ajax
                url: window.location.pathname
                type: 'post'
                dataType: 'json'
                data: 'search_id=' + val + '&search_column=Id&sobject=Country__c&columns=["Name"]'
                error: (jqXHR, textStatus, errorThrown) ->
                        alert('Error: ' + textStatus + ': ' + errorThrown)
                success: (c_data, textStatus, jqXHR) ->
                        data[key] = c_data['Name']
                        console.log(c_data['Name'])
                        console.log(key)
        )
defer = $.when.apply($, requests)

我省略了defer.done函数。console.log信息的结果如下:

China P.R. 
Country_of_Residence__c 
China P.R. 
Country_of_Residence__c

而不是预期的

China P.R. 
Correspondence_Country__c
China P.R. 
Country_of_Residence__c

我的咖啡说明书有问题吗?

EDIT:看起来这与ajax请求或将ajax请求推送到requests数组有关。在推送ajax调用之前,我在函数的开头添加了几个console.log(),它产生了以下信息:

Correspondence_Country__c
a063000000CZoZHAA1
Country_of_Residence__c
a063000000CZoZHAA1 

$.ajax是异步的(除非另有说明,但您不希望这样做)。这意味着循环将在ajax调用完成之前结束。当ajax调用最终结束时,"key"将是数组的最后一个值。(JS没有块作用域)。

使用咖啡的do来保持正确的值。

for key, val of {'Correspondence_Country__c':data['Correspondence_Country__c'], 'Country_of_Residence__c': data['Country_of_Residence__c']}
  do (key) ->
    # your code