谷歌应用脚​​本是否同步? [英] Is google apps script synchronous?

查看:183
本文介绍了谷歌应用脚​​本是否同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是同时学习JavaScript和Google Apps脚本的Java开发人员。作为新手,我学习了JavaScript的语法,而不是它的实际工作方式,而且我很乐意在Google Apps脚本中入侵,并像Java一样顺序编写代码并同步编写代码。我的所有代码都与此类似:(粗略地简化为显示我的意思)


$ b

  function doStuff() {
var url ='https:// myCompany / api / query?term< term& search';
var json = getJsonFromAPI(url);
Logger.log(json);
}

function getJsonFromAPI(url){
var response = UrlFetchApp.fetch(url);
var json = JSON.parse(response);
返回json;
}

它起作用了!它工作得很好!如果我没有继续学习JavaScript,我会说它像钟表一样工作。但JavaScript并不是一个钟表机构,它是光荣的异步的,据我所知,这根本不应该工作,它会编译,但记录 json 变量应该记录未定义,但它记录了JSON没有问题。



注意: 该代码在Google表格的脚本编辑器中编写并执行。



这是为什么?

解决方案

虽然Google Apps脚本实现了ECMAScript 5的一个子集,但没有任何东西强制它是异步的。



虽然JavaScript的主要优势在于它的异步性,但Google开发者似乎已经放弃了这一点,转而采用更简单,更直接的API。



UrlFetchApp 方法是同步的。它们返回一个 HttpResponse 对象,并且它们不需要回调。这显然是一个API决定。


I'm a Java developer learning JavaScript and Google Apps Script simultaneously. Being the newbie I learned the syntax of JavaScript, not how it actually worked and I happily hacked away in Google Apps Script and wrote code sequentially and synchronous, just like Java. All my code resembles this: (grossly simplified to show what I mean)

function doStuff() {
  var url = 'https://myCompany/api/query?term<term&search';
  var json = getJsonFromAPI(url);
  Logger.log(json);
}

function getJsonFromAPI(url) {
  var response  = UrlFetchApp.fetch(url);
  var json = JSON.parse(response);
  return json;
}

And it works! It works just fine! If I didn't keep on studying JavaScript, I'd say it works like a clockwork. But JavaScript isn't a clockwork, it's gloriously asynchronous and from what I understand, this should not work at all, it would "compile", but logging the json variable should log undefined, but it logs the JSON with no problem.

NOTE:

The code is written and executed in the Google Sheet's script editor.

Why is this?

解决方案

While Google Apps Script implements a subset of ECMAScript 5, there's nothing forcing it to be asynchronous.

While it is true that JavaScript's major power is its asynchronous nature, the Google developers seem to have gave that up in favor of a simpler, more straightforward API.

UrlFetchApp methods are synchronous. They return an HttpResponse object, and they do not take a callback. That, apparently, is an API decision.

这篇关于谷歌应用脚​​本是否同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆