Error in a Function with callback

Asked

Viewed 132 times

0

js and getting into callback I’m having a problem error:

TypeError: callback is not a function
    at Timeout._onTimeout (C:\Users\SpiriT\Documents\estudo\callback\index.js:4:16)
    at ontimeout (timers.js:436:11)
    at tryOnTimeout (timers.js:300:5)
    at listOnTimeout (timers.js:263:5)
    at Timer.processTimers (timers.js:223:10)
PS C:\Users\SpiriT\Documents\estudo\callback> 

my code:

function getUser(callback){
    setTimeout( () => {
        return callback(null, {
            id: 1,
            nome: 'gabriel',
            dataNascimento: new Date()
        })
    },1000)
}

function getPhone(idUsuario,callback){ //callback sempre no ultimo param
    setTimeout( () => {
        return callback(null, {
            telefone:'99492566',
            dd:73
        })
    },1000)
}

function getAddress(idUsuario,callback){
    setTimeout( () => {
        return callback(null,{
            rua: 'Fatima',
            numero: '197'
        })
    },1000)
}

getUser(function resolveUser(error,usuario){
    if(error){
        console.error('fail in user', error);
        return;
    }
    getPhone(usuario.id, function resolvePhone(error1,phone){
        if(error1){
            console.error('fail in phone', error1);
            return;
        } 
    })
    getAddress(usuario.id, function resolveAddrsss(error2,address){
        if(error2){
            console.error('fail in address', error2);
            return;
        } 
    })
})

const usuario = getUser();
const phone = getPhone();
const address = getAddress();
  • You must pass the parameter inside the timeout after the time in milliseconds. Example: }, 1000, callback)

  • continued with the same error @Leonardogetulio

  • It turns out that in getUser(), getPhone() and getAddress() you’re not passing the callback, therefore the error. To fix, add if (!(callback instanceof Function)) return before all the Return callback(..)

  • I found strange I was following a course and I made qse equal just changing name of functions and etc and had given error went to check the video and had done just like .

  • @Valdeirpsr you could answer how it would look?

2 answers

1


It turns out that when the code const usuario = getUser(); is executed, the function getUser should receive a callback. There are some ways to correct this error.

In the first, we can verify whether the variable callback is or is not a function. For this, we can use the operator instanceof.

With this operator, we can verify if a given variable is of the same type as a given class or function.

function getUser(callback){
    /**
     * Verifica o callback é uma função
     * Caso não seja, retorna vazio e
     * não executa a função `setTimeout`
     */
     if (!(callback instanceof Function)) return

    setTimeout( () => {
		  return callback(null, {
            id: 1,
            nome: 'gabriel',
            dataNascimento: new Date()
        })
    },1000)
}

function getPhone(idUsuario,callback){ //callback sempre no ultimo param
    /**
     * Verifica o callback é uma função
     * Caso não seja, retorna vazio e
     * não executa a função `setTimeout`
     */     
     if (!(callback instanceof Function)) return
    
    setTimeout( () => {
        return callback(null, {
            telefone:'99492566',
            dd:73
        })
    },1000)
}

function getAddress(idUsuario,callback){
    /**
     * Verifica o callback é uma função
     * Caso não seja, retorna vazio e
     * não executa a função `setTimeout`
     */     
    if (!(callback instanceof Function)) return
    
    setTimeout( () => {
        return callback(null,{
            rua: 'Fatima',
            numero: '197'
        })
    },1000)
}

const usuario = getUser();
const phone = getPhone();
const address = getAddress();

getUser(function resolveUser(error,usuario){
    if(error){
        console.error('fail in user', error);
        return;
    }
    getPhone(usuario.id, function resolvePhone(error1,phone){
        if(error1){
            console.error('fail in phone', error1);
            return;
        } 
    })
    getAddress(usuario.id, function resolveAddrsss(error2,address){
        if(error2){
            console.error('fail in address', error2);
            return;
        } 
    })
})

Beyond the above form, we can pass a Arrow Function empty. That way we will be passing a callback, avoiding mistakes.

function getUser(callback) {
  setTimeout(() => {
    return callback(null, {
      id: 1,
      nome: 'gabriel',
      dataNascimento: new Date()
    })
  }, 1000)
}

function getPhone(idUsuario, callback) { //callback sempre no ultimo param
  setTimeout(() => {
    return callback(null, {
      telefone: '99492566',
      dd: 73
    })
  }, 1000)
}

function getAddress(idUsuario, callback) {
  setTimeout(() => {
    return callback(null, {
      rua: 'Fatima',
      numero: '197'
    })
  }, 1000)
}

getUser(function resolveUser(error, usuario) {
  if (error) {
    console.error('fail in user', error);
    return;
  }
  getPhone(usuario.id, function resolvePhone(error1, phone) {
    if (error1) {
      console.error('fail in phone', error1);
      return;
    }
  })
  getAddress(usuario.id, function resolveAddrsss(error2, address) {
    if (error2) {
      console.error('fail in address', error2);
      return;
    }
  })
})

const usuario = getUser( _ => {} ); //Informa uma arrow function
const phone = getPhone( null, _ => {} ); //Informa uma arrow function
const address = getAddress( null, _ => {} ); //Informa uma arrow function

0

The solution is not to change the functions to finish if callback is not defined. In this context it is to treat the symptoms without treating the cause. In some places in the country they call it gambiarra.

The error happens precisely in these calls, that you do not define the function callback:

const usuario = getUser();
const phone = getPhone();
const address = getAddress();

But these lines of code are loose and have no purpose. So why edit your solution to solve a problem created by a code that shouldn’t even exist? Just delete these lines.

function getUser(callback) {
  setTimeout(() => {
    return callback(null, {
      id: 1,
      nome: 'gabriel',
      dataNascimento: new Date()
    })
  }, 1000)
}

function getPhone(idUsuario, callback) {
  if (!(callback instanceof Function)) return

  setTimeout(() => {
    return callback(null, {
      telefone: '99492566',
      dd: 73
    })
  }, 1000)
}

function getAddress(idUsuario, callback) {
  setTimeout(() => {
    return callback(null, {
      rua: 'Fatima',
      numero: '197'
    })
  }, 1000)
}

getUser(function(error, usuario) {
  if (error) {
    console.error('fail in user', error);
    return;
  }

  console.log("Usuario", usuario);

  getPhone(usuario.id, function(error1, phone) {
    if (error1) {
      console.error('fail in phone', error1);
      return;
    }

    console.log("Telefone", phone);
  })

  getAddress(usuario.id, function(error2, address) {
    if (error2) {
      console.error('fail in address', error2);
      return;
    }

    console.log("Endereço", address);
  })
})

I added some console.log to display the data obtained in case of success.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.