i am practicing callback functions and i want to know how do i access the result of a function, indide of a callback function without using promises…
const mdn = (name) => {
if(typeof name === 'string') {
resolve()
}
else {
reject()
}
}
const resolve = function() {
console.log(`Hello ${name}`)
}
const reject = function() {
console.log(`invalid Name`)
}
mdn('ok')
How do i access the result of calling the function, inside the callback function itself ?
2
Answers
A callback function is one that is passed as an argument to a function which then calls it. You don’t have any of those.
A function has access to the variables that are:
Your variable (
name
) exists only in the scope of themdn
function.resolve
andreject
are not defined insidemdn
. They do not have access toname
.You can change where those functions are defined, so the
name
variable is in scope.You can pass the value of the variable as an argument to
resolve
andreject
.Earlier I pointed out that your functions are not callbacks. Making them callback functions wouldn’t make a difference to the variable scope.
actually
Promise
,callback
has nothing to do with thisyou need to pass parameters to
resolve
: