Slack 螺栓 - HTTP 请求 - 异步

Slack bolt - HTTP Request - assyncronous

我正在将 Slack Bolt Framework 与 Javascript 一起使用,并且我正在尝试执行 http 请求。问题是即使使用 async/await,代码也没有等待请​​求完成。它总是给出 'undefined'

我请求的端点是 'https://viacep.com.br/ws/' + cep + '/json/' 其中 cep 是用户设置的参数(比如例如 09784100)。

调用http请求函数的代码如下:

// 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.`
    });
  }
  
});

这里是发出 http 请求的代码:

//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;
  
}

您正在混合回调和 async/await 方法之间的异步模型。相反,试试这个(使用具有异步本机机制的超级代理来简化我正在编写的代码):

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;
}

作为替代方案,如果您想坚持使用 ,您也可以使用 Promise