Question

Say I want to create some callback hell, such as :

function handleUserInput(callback) {
    ...
} 

function get(uri, callback) {
    ...
}

function processResponseInWorker(callback) {
    ....
}

function updateIndexedDB(callback) {
    ...
}

function updateUI() {
    ...
} 

handleUserInput(get(hot_uri,processResponseInWorker(updateIndexedDB(updateUI()))));

This is mostly academic since the stack only gets 5 high.

In fact, is there even a stack at all? Since these calls will return immediately, and the callback will only be invoked, outside of these contexts, by whatever asynchronous tasks these functions perform.

Okay, just say there IS a call stack here, if each callback was forced to execute inside a setTimeout(func,0) then the calling function would return immediately, the whole chain would return immediately and the functions would be executed off the setTimout queue.

Is that correct?

Was it helpful?

Solution

setTimeout will not call the provided functions unless there is no other code running.

As is demonstrated in this code the timeout, although it is a 0 millisecond delay, will not execute until no other code is being executed. That is the nature of classic javascript (synchronized).

console.log(1);
setTimeout(function() {
    console.log(2);
}, 0);
console.log(3);
for(var i = 4; i < 100; i++) {
    console.log(i);
}

Initially lets assume the depth is 0. Let's assume that no functions other than the callbacks and the functions in the original code are called

updateUI()

Call the function updateUI our depth becomes 1. We return a function from this function and our depth becomes 0 again and we have something that essentially looks like this.

updateIndexedDB(function(){})

So we call updateIndexedDB and our depth becomes 1 which calls the provided callback function and our depth becomes 2. The callback returns and depth becomes 1 and updateIndexedDB returns a functions so that we have something looks like this.

processResponseInWorker(function() {})

Similar process occurs until we have this

get(hot_uri, function() {})

Again the same thing until we have this

handleUserInput(function() {})

Without using timeout the max depth i observe is 2 but using timeouts on your callbacks (which i don't know if you can do because i don't know if your callbacks give you future callbacks) your max is 1 since the callbacks will individually be executed after all code has been executed (on their own stack).

I feel like you meant to write your code this way

handleUserInput(function() {
    get(hot_uri , function() {
        processResponseInWorker(function() {
            updateIndexedDB(function() {
                updateUI();
            });
        });
    });
});

which would result in a depth of 6 again unless you use timeouts which would result in a stack size of 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top