【问题标题】:Javascript (NodeJS): How to get data back from a Google Calendar API callbackJavascript (NodeJS):如何从 Google Calendar API 回调中取回数据
【发布时间】:2017-12-01 18:03:42
【问题描述】:

关于这个例子:https://developers.google.com/google-apps/calendar/quickstart/nodejs

我想更改 listEvents 以返回事件的 JSON 数组。

目前是这样称呼的:

authorize(JSON.parse(content), listEvents);

其中“listEvents”是传递给回调的函数:

function authorize(credentials, callback) {

我尝试向 ListEvents 添加一个 return 语句,然后:

var jsonEvents = authorize(JSON.parse(content), listEvents);
console.log("Json Events="); 
console.log(jsonEvents); 

我知道它对我来说是异步的,因为我在 listEvents 函数的 console.log 输出之前得到了上面的 console.logs。 我也尝试输入“等待”这个词,但没有运气。

我尝试在 listEvents 中设置一个额外的参数:

var jsonEvents; 
authorize(JSON.parse(content), listEvents(jsonEvents));
console.log("Json Events="); 
console.log(jsonEvents); 

导致“typeError:回调不是函数”。

更新:根据@Tuches 的回答,我得到了这个工作。想知道是否有必要扩展这么远。

  authorize(JSON.parse(content), function(token) {
      console.log("Got Token"); 
      //console.log(token);
      listEvents(token, function(jsonResult) {
          console.log("Json Callback Events="); 
          console.log(jsonResult); 
      }); 
    });

【问题讨论】:

    标签: javascript asynchronous callback google-calendar-api


    【解决方案1】:

    我不了解 google 日历 API,但快速阅读它的第二个参数是回调函数。这意味着授权的结果将结束,然后将调用 listEvents。所以实际上你应该做的是要么在 listEvents 中处理这个数据返回,要么你可以修改 listEvents 以返回一个回调,比如:

    function listEvents(auth, callback) {
        // ... implementation of the function
        // When the function is done an there's data to
        // return, callback the data
        callback(data);
    }
    

    这样您就可以通过执行以下操作来处理从 listEvents 返回的数据:

    authorize(JSON.parse(content), listEvents(data, function(response) {
            console.log(response); // <-- return from listEvents    
        })
    );
    

    编辑:对代码的小修正。

    【讨论】:

    • 好的,这是有道理的,但是我在以下 API 库之一中收到此错误:λ node testGoogleCalendarAPI.js E:\GitHub\NealWalters\RabbiJoseph\node_modules\googleapis\lib\apirequest.js: 150 req = authClient.request(选项,回调); ^ TypeError: authClient.request 不是函数
    • 我能够从授权中取回令牌,然后以同步方式调用 listEvents,但 listEvents 更加复杂,因为它有一个来自 calendar.list.events 的回调:function(err, response )。
    • 查看我的更新,得到它的工作,但也许不是最好的方式。
    • 这给出了以下错误:ReferenceError: data is not defined
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    相关资源
    最近更新 更多