重复JavaScript函数并返回初始回调?

问题描述 投票:0回答:1

是否可以在JavaScript中调用一个再次调用自身的函数,并在它再次调用自身后,最终运行初始回调函数?

我将在代码中解释我的意思......

//on page load
getProviderNextAppointment(null, function(nextAppointment) {

    otherFunction(); //<----- how can I always end up back here, no matter what?

});


//getProviderNextAppointment function
function getProviderNextAppointment(startDate, callback) {

    getNextAppointment('provider', startDate, function(data) {

        //if provider has schedule
        if(!$.isEmptyObject(data.AllProviders)) {

            //set provider params
            //nextAppointment = data.x

            //callback
            if(typeof callback === 'function') {
                return callback(nextAppointment); //callback from call on page load
            }

        } else {

            if(data.ErrorCode !== 'StartDateTooFarInFuture') {

                /*---------->
                 * this is where we this function calls itself again;
                 * but when it hits the callback above (provider
                 * has schedule), or when it hits the callback
                 * below (last group of appointments), it
                 * should run the initial callback to
                 * execute otherFunction()
                 <----------*/
                getProvidersNextAppointment(data.LatestDate);

            } else { //hit last group of appointments

                if(typeof callback === 'function') {
                    return callback(null); //callback from call on page load
                }

            }

        }

    });

}

我没有包括getNextAppointment()函数,因为它与问题无关。只知道它正在调用返回约会信息的API,以及我们用作下一个API调用的LatestDatestartDate属性。我们也在寻找对ErrorCode属性的回应,它说它是结果的结束,所以我们不会永远循环。

javascript function callback
1个回答
0
投票

如果你需要保持对初始回调函数的引用,那么你可以通过递归调用将它传递给它。

从这里更改递归调用:

getProvidersNextAppointment(data.LatestDate);

至:

getProvidersNextAppointment(data.LatestDate, callback);

现在,嵌套函数上下文将引用原始回调函数,理论上这可以在递归树中进一步向下级联,直到最终执行回调函数。

© www.soinside.com 2019 - 2024. All rights reserved.