Search code examples
dialogflow-es

Dialogflow is giving error unreachable code after return


I'am fetching the data via axios from mini crypto compare api for getting the crypto prices in dialogflow, but in my fulfillment code I'am receiving this error (if unreachable code after return). If I bring the if section inside the promise, than the agent.add() will not work and it give no response defined for the platform error in the console.

function priceFinder(agent) {
const data = agent.parameters[CRYPTO_NAMES];

let btc = '';
let eth = '';

 return axios.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,BNB,SOL,LUNA&tsyms=USD')
    .then(response => {
        btc = response.data.BTC.USD;
        eth = response.data.ETH.USD;
   
 
 });

if(data === "btc") {
 agent.add(`BTC Price is : ${btc}`); 
  
}
else if(data === "eth") {
  
 agent.add(`ETH Price is : ${eth}`); 
}



}

Solution

  • I was able to get your function working on my side, here is my updated code to your function based on the block you provide:

    used library

    const https = require('https');
    

    main function

      function getBitcoinInfo(agent){ 
        const url= 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,BNB,SOL,LUNA&tsyms=USD';
        
        const req = https.get(url, res => {
        console.log(`statusCode: ${res.statusCode}`);
          let data = ''; 
          res.on('data', (chunk) => {
            data += chunk;
          });
          res.on('end', () => {
            console.log(data); 
            console.log(JSON.parse(data).BTC);
          });
        });
        agent.add(`I found bitcoins!`);
      }
    

    IntentMap

      let intentMap = new Map(); 
      intentMap.set('Get Bitcoin Info', getBitcoinInfo);
      agent.handleRequest(intentMap);
    

    Useful Tips

    • return will execute that last statement and will not proceed further effectively making the rest code lines unreachable.
    • You can check the logs on by going to cloud functions -> my_deployed_ fullfillment -> logs
    • Latest results are always show at the end.
    • If no console message reach the log, make sure your function executes properly
    • Once you parse the json you can pick elements from it and fill variables and add it to your response. You can use JSON parse for it.

    Useful links: