skip to Main Content

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


  1. 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:

    • Defined inside it, including as arguments
    • Exist at the point where it is defined itself (unless they are shadowed).

    Your variable (name) exists only in the scope of the mdn function.

    resolve and reject are not defined inside mdn. They do not have access to name.


    You can change where those functions are defined, so the name variable is in scope.

    const mdn = (name) => {
      const resolve = function() {
        console.log(`Hello ${name}`)
      }
    
      const reject = function() {
        console.log(`invalid Name`)
      }
      if (typeof name === 'string') {
        resolve()
      } else {
        reject()
      }
    }
    
    
    mdn('ok')

    You can pass the value of the variable as an argument to resolve and reject.

    const mdn = (name) => {
      if (typeof name === 'string') {
        resolve(name)
      } else {
        reject(name)
      }
    }
    
    const resolve = function(name) {
      console.log(`Hello ${name}`)
    }
    
    const reject = function(name) {
      console.log(`invalid Name`)
    }
    
    mdn('ok')

    Earlier I pointed out that your functions are not callbacks. Making them callback functions wouldn’t make a difference to the variable scope.

    Login or Signup to reply.
  2. actually Promise, callback has nothing to do with this

    you need to pass parameters to resolve:

    const mdn = (name) => {
        if(typeof name === 'string') {
            resolve(name)
      }
      else {
        reject()
      }
    }
     
     const resolve = function(name) {
            console.log(`Hello ${name}`)
        }
        
     const reject = function() {
            console.log(`invalid Name`)
     }
    
    mdn('ok')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search