【发布时间】: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 页面上,因此可能需要一段时间才能更新。感谢您的帮助。