You cannot use a declared variable outside of an asynchronous context. In this case, the .end(callback) is asynchronous, therefore the value will be set after you log it using console.log.
const result = document.querySelector('.output');
function write(str) {
const span = document.createElement('span');
span.innerText = str;
result.append(span);
}
write("Starting script");
function asyncFn(callback) {
// Simulate a function that takes time to complete but returns immediately
const t = setTimeout(() => {
callback('Finished');
clearTimeout(t);
}, 1000);
}
write("Declaring contextual variable");
let contextVar;
function asyncFnCaller() {
asyncFn((response) => {
write(`Result of the callback: ${response}`);
contextVar = response;
write(`contextVar inside the callback: ${contextVar}`);
})
}
write("Invoking the asyncFnCaller");
asyncFnCaller();
write(`Content of the context variable: ${contextVar}`)
In this code, the asyncFnCaller is like the .end function.
Try to understand how the example works and see if you can figure out why it doesn’t work .