Skip to main content

Callbacks

Promises/Async/Await: Callbacks


Can you Explain the function and syntax of the async function in JavaScript?

View Answer:
Interview Response: An async function is a function declared with the async keyword, and the await keyword gets permitted within them. The async and await keywords enable asynchronous, promise-based behavior, avoiding the need to configure promise chains explicitly. Async functions may also get defined as expressions.

Code Example:

function resolveAfter2Seconds() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}

async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}

asyncCall();

How do callbacks work in JavaScript?

View Answer:
Interview Response: A callback is a function passed as an argument to another function, and a callback function can run after another function has finished. JavaScript functions execute in the sequence they get called, not in the defined sequence.

note

Functions running in parallel with other functions are called asynchronous.


How can we load two scripts sequentially: the first one and the second one after it?

View Answer:
Interview Response: The natural solution would be to put the second script call inside the callback. Nesting the callback helps control the flow of the script loads. After the external script is complete, the callback initiates the inner one.

Code Example:

loadScript('/my/script.js', function (script) {
alert(`Cool, the ${script.src} is loaded, let's load one more`);

loadScript('/my/script2.js', function (script) {
alert(`Cool, the second script is loaded`);
});
});

There are times when internal/external scripts fail to load. Is there a way, in JavaScript, to handle resource (scripts) loading errors?

View Answer:
Interview Response: Yes, script loading errors get handled in a callback with the script.onerror event handler.

Code Example:

function loadScript(src, callback) {
let script = document.createElement('script');
script.src = src;

script.onload = () => callback(null, script);
script.onerror = () => callback(new Error(`Script load error for ${src}`));

document.head.append(script);
}

What is the best alternative to nested resource loading in asynchronous coding?

View Answer:
Interview Response: Nested calls can become tedious and messy. The best alternative is to make every action a standalone function, making our code easier to manage and debug.

Technical Response: It looks fine for one or maybe two nested calls. As calls become nested, the code becomes more profound and increasingly more challenging to manage, especially if we have real code that may include more loops, conditional statements, and other implementations. The best alternative to alleviate the problem is to make every action a standalone function. This approach makes the code easy to manage and debug, and there are some performance advantages to boot.

Code Example:

loadScript('1.js', step1);

function step1(error, script) {
if (error) {
handleError(error);
} else {
// ...
loadScript('2.js', step2);
}
}

function step2(error, script) {
if (error) {
handleError(error);
} else {
// ...
loadScript('3.js', step3);
}
}

function step3(error, script) {
if (error) {
handleError(error);
} else {
// ...continue after all scripts are loaded (*)
}
}