Search code examples
javascriptslackslack-apibolt

Slack bolt - HTTP Request - assyncronous


I'm using Slack Bolt Framework with Javascript and I'm trying to do a http request. The problem is that the code is not waiting the request to be finished even using async/await. It always gives 'undefined'

The endpoint I'm requesting is 'https://viacep.com.br/ws/' + cep + '/json/' where cep is a parameter set by the user (like 09784100 for instance).

Here is the code that call the http request function:

// Action listener function called when an interactive component with action_id of “submitCEPButton” is triggered
app.action('submitCEPButton', async ({ ack, body, client, say, text}) => {
  
  // Acknowledge action request before anything else
  await ack();
  
  let channelID = body.channel.id
  let userID    = body.user.id
  var cep       = body.state.values['inputBlock']['inputCEP'].value
      
  if(isValidCep(cep)){
    //console.log('É valido');
    let data = await getAddressData(cep);
    console.log(data);
    
    await say({
      "blocks": [
        {
          "type": "header",
          "block_id": "headerBlock",
          "text": {
            "type": "plain_text",
            "text": "🔍 Busca de Endereço - Resultado",
            "emoji": true
          }
        },
        {
          "type": "divider",
        },
        {
          "type": "section",
          "text": {
            "type": "mrkdwn",
            "text": "*Rua: * " + data.logradouro
          }
        },
        {
          "type": "section",
          "text": {
            "type": "mrkdwn",
            "text": "*Complemento: * " + data.complemento
          }
        },
        {
          "type": "section",
          "text": {
            "type": "mrkdwn",
            "text": "*Bairro: * " + data.bairro
          }
        },
        {
          "type": "section",
          "text": {
            "type": "mrkdwn",
            "text": "*Cidade: * " + data.localidade
          }
        },
        {
          "type": "section",
          "text": {
            "type": "mrkdwn",
            "text": "*Estado: * " + data.uf
          }
        }
      ]
    })
  }
  else{
    
    await client.chat.postEphemeral({
      channel: channelID,
      user: userID,
      text: `<@${userID}> ❌ CEP inválido. Verifique o CEP digitado e tente novamente.`
    });
  }
  
});

And here is the code that make the http request:

//Make http request
async function getAddressData(cep){
    
  var url = 'https://viacep.com.br/ws/' + cep + '/json/';
  let data = '';
  
  https.get(url, res =>{
          
      res.on('data', chunk => {
        data += chunk;
      });
    
      res.on('end', () => {
        data = JSON.parse(data);
        //return data;
      })
  })
  
  return data;
  
}

Solution

  • You're mixing async models between callbacks and async/await methodology. Instead, try this (using superagent, which has async native mechanisms, to simplify the code I'm writing):

    const superagent = require('superagent');
    
    async function getAddressData(cep){
        
      const url = 'https://viacep.com.br/ws/' + cep + '/json/';
    
      const response = await superagent.get(url);
    
      return response.body;
    }
    

    As an alternative, you could also use a Promise if you want to stick with vanilla Javascript HTTP Request.