2016-01-11 16 views
0

即時通訊使用CasperJS的eachThen()方法,我需要知道下一個迭代項的值。CasperJS每個接下來(未來)響應數組的值

我有物品這樣的:

array = [ 

[22,"blah"], 
[22,"blah"], 
[23,"blah"], 
[24,"blah"], 
[24,"blah"], 
[24,"blah"] 
] 

我生成每項的組中的一個文件(由分組[0])。

我的第一種方法是與前一個項目的實際項目在迭代開始比較,如果[0]是不同的生成文件,像這樣:

//previousItem was initilizated = to actualItem 

    casper.eachThen(array , function (response) { 
      var actualItem = response.data 

     casper.then(function(){ 
      if(actualItem[0] != previousItem[0]){ 
       var filename = previousItem[0]+"file.html" 
       var f = fs.open(filename, 'a'); 
       f.write(stdFile); 
       f.close(); 
       previous = actualItem 
      } 
     }); 

//operations that prepares stdFile to be created 

問題出現在末尾的週期,因爲即時比較實際與以前,最後一組將不會生成任何文件(當然,最後2項將具有相同的[0],並在此之後,週期將結束)

我的解決方案在這裏是要求下一個項目而不是以前的,並在末尾生成文件每次迭代,但我不知道如何告訴卡斯帕給我的數組中的actualItem + 1的項目。

我會試着解決這個迭代在paralel裏面的同一個數組,並返回實際值+ 1,但也許有一種方法可以使用響應變量。

的結果必須是3個文件:22file.html,23file.html和24file.html 有很多的要求,使

,所以我需要贏得任何第二,我可以。

如果你有另一種方法來實現這一點,請讓我知道。

PS:對不起,我的英語,它不是我的母語

感謝

+0

你能展示你的代碼的更大一部分嗎?你評論*「// previousItem被初始化=到actualItem」*沒有意義,因爲當時還沒有定義「actualItem」。 –

回答

0

我的第一種方法是太複雜了,可能是因爲我沒有睡這麼多,這些天。

這是我做過什麼:

cajIndex = 0; 

//this block generates the file if actualItem (or actualCajero is the same) is not undefined and the actualItem[0] is not the same as the next item 

if (actualCajero != undefined) 
     { 
      if (actualCajero[0] != cajerosArray[cajIndex][0]){ 
       casper.then(function(){ 

        var filename = "Ventas local"+" "+nombreLocal+"_"+actualDay[1]+"-"+actualDay[2] 
        stdFile = '<h1>'+filename+'</h1> <table border="1">'+ stdTable + '</table>'; 
        this.echo("generando archivo "+filename); 
        var f = fs.open(filename+".xls", 'a'); 
        f.write(stdFile); 
        f.close(); 
        stdTable = ""; 
        stdFile = ""; 

       }); 
      } 
     } 

//after this i do my operations , ask again for file creating at the end but now if the next item is undefined, if it is undefined creates the file then 

cajIndex++ 

和解決一切問題的關鍵在0宣稱索引和請求的文件分配actualItem到響應之前創建,然後在年底再次問最後一項。

希望它有幫助