Google Appscript / UrlFetchApp.fetchAll()函数是否可以同步运行?

Stu*_*Stu 1 javascript google-apps-script google-data-studio

我遇到的问题是,我要发出许多API请求,由于要返回的数据大小,所有这些请求都需要花费几秒钟的时间才能返回,并且UrlFetchApp.fetchAll(..)仅返回一个空JS对象数组,例如:[{}, {}, {}, ...]

我的请求数组看起来像这样(为清楚起见而格式化):

requests = [
  {
    validateHttpsCertificates: false,
    url: 'https://url.com/api/v2/api_key/endpoint/action?params1=false&params2=true'
  },
  {
    validateHttpsCertificates: false,
    url: 'https://url.com/api/v2/api_key/endpoint/action?params3=false&params4=true'
  }
];
Run Code Online (Sandbox Code Playgroud)

发出我的请求的代码:

responses = UrlFetchApp.fetchAll(requests);

// returns back '[{}, {}]'
console.log(JSON.stringify(responses));
Run Code Online (Sandbox Code Playgroud)

我可以通过数据库确认正在运行API调用,因为AWS RDS性能指标显示数据库查询正在运行,并且我还可以确认API本身通过NewRelic响应为200,这就是我的直觉是m未UrlFetchApp.fetchAll()正确使用GAS / 。

因此,我想知道:

  1. GAS是否同步运行,也就是.fetchAll()在运行console.log(...)线路之前会等待返回?
  2. 我真的打fetchAll正确吗?目前不知所措,而Google Appscript文档充其量是微不足道的。

预先感谢您的帮助。

编辑:

我成功使用fetchAll 迁移到fetch,例如:

// synchronously fetching one by one
requests.map(request => UrlFetchAll.fetch(request.url, { validateHttpsCertificates: false });
Run Code Online (Sandbox Code Playgroud)

Tan*_*ike 5

这个答案怎么样?

回答问题1:

fetchAll方法可用于异步处理。参考如果要在同步处理中使用UrlFetchApp,请UrlFetchApp.fetch()循环使用。

回答问题2:

我认为您对fetchAll方法的要求是正确的。为了从中检索响应UrlFetchApp.fetchAll(requests),如何进行以下修改?

修改后的脚本:

var responses = UrlFetchApp.fetchAll(requests);
var res = responses.map(function(e) {return e.getContentText()});
console.log(JSON.stringify(res)); //  or Logger.log(JSON.stringify(res));
Run Code Online (Sandbox Code Playgroud)
  • 在此修改中,getContentText()用于每个响应。
  • 响应的顺序与请求的顺序相同。

参考文献:

如果我误解了您的问题,而这不是您想要的结果,我深表歉意。