Google Appscript / UrlFetchApp.fetchAll()函数是否可以同步运行? 修改后的脚本:

我遇到的问题是我要发出许多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'
  }
];

发出请求的代码:

responses = UrlFetchApp.fetchAll(requests);

// returns back '[{},{}]'
console.log(JSON.stringify(responses));

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

所以,我想知道:

  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 });
ni593010606 回答:Google Appscript / UrlFetchApp.fetchAll()函数是否可以同步运行? 修改后的脚本:

这个答案怎么样?

问题1的答案:

fetchAll方法可用于异步处理。 Ref如果要在同步处理中使用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));
  • 在此修改中,getContentText()用于每个响应。
  • 响应顺序与请求顺序相同。

参考:

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

本文链接:https://www.f2er.com/3113731.html

大家都在问