Javascript与回调同步执行异步调用有问题

时间:2015-05-18 22:51:32

标签: javascript asynchronous

在阅读了这个帖子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);
}

如何让两个(​​)等到一个()完成?我仍然看到"延迟2"在我看到"延迟1"之前。

编辑:以上是我想要做的简单示例,只是尝试为回调做一个问候世界。我试图像这样应用它:

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(),它似乎仍然无效。

1 个答案:

答案 0 :(得分:1)

您需要移动回调:

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

setTimeout的意思是它是异步的,所以它不会阻止你的代码继续。您可以在one的{​​{1}}功能中调用回调。

fiddle

中查看它
相关问题