【问题标题】:How do I have an asynchronous variable inside a synchronous loop?如何在同步循环中有一个异步变量?
【发布时间】:2020-07-09 03:17:10
【问题描述】:

变量 ids 是一个具有不同电子表格 id 的数组。我将它包装在请求周围,因为我想在多个电子表格上做同样的事情,但是,一旦在请求中,id 就会变得同步并保持为 ids 数组中的最后一个元素。我想让它使 id 是异步的并且可以更改,以便我可以对多个 id 进行请求。

for(var i = 0; i < num; i++) {
      var id = ids.slice(i, i+1);
      var params = {
        spreadsheetId: id,
        ranges: ['A3:L'],
        includeGridData: true,
      };

      var request = gapi.client.sheets.spreadsheets.get(branchParams);
      request.then(function(response) {
        console.log(id);

【问题讨论】:

    标签: javascript asynchronous google-sheets google-api synchronous


    【解决方案1】:

    试试这个:

    const getSheets = (ids) => {
      return Promise.all(
        ids.map(id => {
          const params = {
            spreadsheetId: id,
            <...>
          }
          return gapi.client.sheets.spreadsheets.get(params)
        })
      )
    }
    

    这将为列表中的每个 id 调用一次 api,并在 promise 中返回响应列表。你可以像这样使用这个函数:

    const doStuffWithSheets = async () => {
      const ids = [1, 2, 3]
      const sheetResponses = await getSheets(ids);
      sheetResponses.forEach(response => {
        console.log(response)
      })
    }
    

    一些文档供参考:

    Promise.all():https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

    map():https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    异步函数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    【讨论】:

    • 我得到了这个工作,但我该如何去控制台。在 forEach 循环中记录每个 id?谢谢。
    • 它应该在响应中。我认为响应应该是这样的:developers.google.com/sheets/api/reference/rest/v4/… 你也可以使用console.log(JSON.stringify(response, null, 2)); 打印完整的响应,看看里面有什么
    猜你喜欢
    • 2018-07-29
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2015-04-18
    • 2017-06-29
    • 2018-09-18
    • 2016-12-28
    • 2018-10-17
    相关资源
    最近更新 更多