簡體   English   中英

如何使用異步模塊在node.js中異步多次在循環中運行函數

[英]How to run a function in a loop multiple times asynchronously in node.js using the async module

我正在使用google-spreadsheet模塊讀取多個google文檔。 這涉及遍歷我保存在json文件中的每個模塊的所有憑據,然后提取電子表格。 因此,如果我的json文件中有10個電子表格憑據,則需要在循環中使用這些詳細信息調用該函數10次。

然后,我將保存這些電子表格中的信息。 我需要異步執行此操作。 如何實現這一目標,也許使用異步模塊? 我試圖了解此模塊的隊列方面,但沒有太多意義。

 for (var i = 0; i < sheets.length; i++) {

    // All of the below could be put in a separate function that needs to be run asynchronously 

    var sheetID=sheets[i]
    // spreadsheet key is the long id in the sheets URL
    var doc = new GoogleSpreadsheet(sheetID);

    doc.useServiceAccountAuth(creds, function(err) {
      if (err) {
        console.log(err);
        return
      }
      doc.getInfo(function(err, info) {
        if (err) {
          return console.log(err);
        }
        sheet = info.worksheets[0];

        sheet.getRows({
         orderby: "marketname",
          start: 0
        }, function(err, row_data) {
          for (var i = 0; i < row_data.length; i++) {
            console.log(row_data[i].marketname);
          }
        })
      })
    })
  }

因此,如果我正確理解,您想要執行的操作是異步for循環。 這意味着您需要進行異步處理(此處的所有內容均在注釋下),您需要一個接一個地鏈接在一起。

無需使用異步庫,您可以像本例中那樣

// Async task
function async(arg, callback) {
  //You put in here what needs to be done with each of your data 
}
// Final task: display or save your data in your files
function final() { console.log('Done', results); }

// A simple async series:
var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
//Recursive function that will go through your items.
function series(item) {
  //if there is still some item to work with
  if(item) {
    //call your async function with our current item
    async( item, function(result) {
      //push in the results
      results.push(result);
      //Go to the next item.
      return series(items.shift());
    });
  } else {
    //Otherwise this means we're done, and results[] is populated!
    return final();
  }
}
//Start the treatment
series(items.shift());

希望這可以幫助!

您可以在這篇出色的論文中找到有關某些控制流程的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM