request.execute(function(resp){}); 是什么意思?在 JavaScript 中?

Asp*_*pen 1 javascript api request server

用例是调用(Google Drive)API 来获取数据。我了解执行请求的第一部分。但是为什么我们要传递 aresponse到函数中呢?如果有的话,我们不会得到回应吗?

是否有很好的资源来理解请求/响应以及服务器在概念上是如何工作的?或者有人可以发布一个类比吗?

如何取回响应的属性?

T.J*_*der 5

request.execute(function(resp){}); 是什么意思?

它调用request.execute,传入由函数表达式创建的函数function(resp){}。该示例中的函数不执行任何操作。

但是为什么我们要向函数传递响应呢?

我们不是。

如果有的话,我们不会得到回应吗?

是的,这就是代码的作用。您正在传递一个您写入的函数request.execute它将使用一个给出响应的参数调用该函数。该函数接受该响应resp,您可以在代码中使用它。

传入的函数execute称为callback,因为execute当响应可用时会回调它。这是您要搜索以查找教程等的术语。此外(因为该示例几乎肯定是异步的)您将要查找“异步编程”和类似内容。

下面是一个异步调用回调函数的简单示例:

function execute(callback) {
  setTimeout(function() {
    callback(Math.floor(Math.random() * 100));
  }, 500);
}

snippet.log("Calling execute");
execute(function(resp) {                                // <= This is the part
  snippet.log("Got callback, resp = " + resp);          // <= like your
});                                                     // <= example
snippet.log("Done calling execute, waiting for callback");
Run Code Online (Sandbox Code Playgroud)
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Run Code Online (Sandbox Code Playgroud)

并非所有回调都是异步的。例如,您提供的回调Array#sort是同步的:

var a = [1, 7, 3, 42];

snippet.log("Calling Array#sort, array is: " + a.join(", "));
a.sort(function(a, b) {                                   // <= This is
  snippet.log("Comparing " + a + " and " + b);            // <= the part
  return b - a;                                           // <= like your
});                                                       // <= example
snippet.log("Done calling Array#sort, array is now: " + a.join(", "));
Run Code Online (Sandbox Code Playgroud)
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Run Code Online (Sandbox Code Playgroud)