谷歌应用程序脚本是同步的吗? [英] Is google apps script synchronous?

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

问题描述

我是一名 Java 开发人员,同时学习 JavaScript 和 Google Apps 脚本.作为新手,我学习了 JavaScript 的语法,而不是它的实际工作原理,我很高兴地在 Google Apps Script 中进行了黑客攻击,并按顺序和同步编写代码,就像 Java 一样.我所有的代码都是这样的:(为了表达我的意思而进行了粗略的简化)

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;
}

它有效!它工作得很好!如果我不继续学习 JavaScript,我会说它像发条一样工作.但是 JavaScript 不是发条装置,它是非常异步的,据我所知,这根本不起作用,它会编译",但是记录 json 变量应该记录未定义,但它记录了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.

注意:

代码在 Google Sheet 的脚本编辑器中编写和执行.

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

这是为什么?

推荐答案

虽然 Google Apps Script 实现了 ECMAScript 5 的一个子集,没有什么强迫它是异步的.

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

虽然 JavaScript 的主要威力确实在于其异步特性,但 Google 开发人员似乎已经放弃了这一点,转而采用更简单、更直接的 API.

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

UrlFetchApp 方法是同步的.它们返回一个 HttpResponse 对象,并且不接受回调.显然,这是一个 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天全站免登陆