简体   繁体   中英

nodejs callback issue.. not a function

I am currently learning NodeJS and working on a mini app, trying to understand callback. However I keep getting the error:

  callback(undefined,price);
      ^TypeError: callback is not a function

This is my code :

var getCoin = (coin, callback) => {

  request({url:`https://https://rest.coinapi.io/${coin}&ssr=USD`,

  json: true
  }, (error, response, body) => {


    if(error){
      callback("error");

    }
    else if (response.statusCode == 200) {
      let price = body.RAW[coin].USD.PRICE;
      callback(undefined,price);

    }
  })
};

app.get('/', (req, res) => {
  coin.getCoin('BTC', ()=> {
    res.render('index.hbs', {
      coin:'Bitcoin',
      price: coin.getCoin('BTC')

    });
  });
});

Try this code:

app.get('/', (req, res) => {
    coin.getCoin('BTC', (err, price)=> {
        res.render('index.hbs', {
            coin:'Bitcoin',
            price: price

        });
    });
});

I am assuming coin.getCoin accepts two arguments, second argument is callback which itself needs to accept args to work properly. Now in app.get('/' you called coin.getCoin and passed an anonymous function that will be treated as callback for it, if coin.getCoin does its job correctly then price will have the value that will eventually be passed to index.hbs and res.render will do the rest job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM