【问题标题】:Javascript trouble with callbacks to execute asynchronous calls synchronouslyJavascript 问题与回调同步执行异步调用
【发布时间】:2015-07-30 14:18:20
【问题描述】:

阅读此线程How should I call 3 functions in order to execute them one after the other? 后,我仍然不确定为什么这不起作用并且无法使异步调用同步:

function testCallBack(){
    one(two);
}
function one(callback){
    setTimeout(function(){alert("delay 1")},2000);
    callback();
}
function two(){
    setTimeout(function(){alert("delay 2")},1000);
}

如何让 two() 等到 one() 完成?在看到“延迟 1”之前,我仍然看到“延迟 2”。

编辑:上面是我想要做的一个简化示例,只是想为回调做一个 hello world。我正在尝试这样应用它:

function add() {
    addCalendar(getCalendarID);
}
function addCalendar(callback) {
    var req = gapi.client.calendar.calendars.insert(
    {
        "resource": 
        {"summary": "McGill Schedule",
            "description": "Winter 2015",
            "timezone": "Canada/Montreal"}
    });
    req.execute(function(resp) {
        console.log("added calendar");
        callback();
    });
}
function getCalendarID() {
    var req = gapi.client.calendar.calendarList.list({});
    req.execute(function(resp) {
        for (var i = 0; i < resp.items.length; i++) {
            if (resp.items[i].summary === "McGill Schedule") {
                console.log("Mcgill Sched id: " + resp.items[i].id);
                calendarID = resp.items[i].id;
                break;
            }
        }
    });
}

即使在 api 调用的响应中使用 callback() 似乎仍然不起作用。

【问题讨论】:

  • “完成”对您意味着什么?如果你想等到alert() 之后,那么setTimeout 函数就是你需要调用callback() 的地方。
  • @Bergi 看到我上面的编辑 - 当我运行时,我什至没有看到 console.log("Mcgill Sched ...") 出于某种原因。
  • 你能给我指点gapi.client.calendar...的一些文档吗?
  • gapi.client 是 google apis 的 javascript 客户端(这里:developers.google.com/api-client-library/javascript/start/…),日历特定的东西在这里developers.google.com/google-apps/calendar/v3/reference
  • 别介意它神奇地开始工作!我将此托管在 github 页面上,因此可能需要一段时间才能更新。感谢您的帮助。

标签: javascript asynchronous


【解决方案1】:

你需要移动回调:

function testCallBack(){
    one(two);
}
function one(callback){
    setTimeout(function(){
        alert("delay 1");
        callback();
    },2000);
}
function two(){
    setTimeout(function(){alert("delay 2")},1000);
}

setTimeout 的要点是它是异步的,因此它不会阻止您的代码继续执行。不过,您可以从onesetTimeout 函数中调用回调。

查看它在 fiddle

中的工作

【讨论】:

  • 谢谢,这是有道理的。不过,我似乎仍然无法将其应用于我的谷歌日历 api 调用。
猜你喜欢
  • 2013-05-15
  • 2012-01-02
  • 2017-03-19
  • 1970-01-01
  • 2010-10-25
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多