Необработанное отклонение обещания при использовании бота Microsoft Framework - PullRequest
1 голос
/ 12 апреля 2020

Я использую Microsoft Bot Framework и пытаюсь интегрировать его с внешними HTTP-вызовами.

Однако, когда я вызываю BotWorker.say в запросе обработчика BotKitConversation, я начинаю получать

 (node:5711) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot perform 'get' on a proxy that has been revoked

Ниже мой код

В обратном вызове моей функции-обработчика я получаю некоторые значения, возвращаемые из внешней функции. Затем я пытаюсь выполнить bot.say для возвращенного ответа и получаю вышеупомянутую ошибку.

 myDialog.ask('What would like to hear?', [
    {
        pattern: '.*',
        handler: async (response, convo, bot) => {
            await YoutubeHelper.getChannel(response, convo,async function(channels){
            console.log("value returned " + channels.length);
            try {
            await bot.say('Printing values'); //error comes here

            if (channels.length == 0) {

                await bot.say('No items found.');
              } else {
                await bot.say('This items\'s ID is %s. Its title is \'%s\', and ' ,
                            channels[0].id,
                            channels[0].snippet.title
                            );
              }
            }catch (err) {
                console.log('error occurred' , err);

            }
            });
        }
    }

],  {key: 'name'});
}

, где myDialog является объектом BotkitConversation.

Ниже приведен код для моего внешнего служебный класс

 /**
 * Lists the names and IDs of up to 10 files.
 *
 * 
 */

var {google} = require('googleapis');

var {myDialog} = require("./bot")

const getChannel = function getChannel(searchTerm, convo,callback) {


    var service = google.youtube({
      version : 'v3',
      auth : '<client id>'});


    service.search.list({
      part: 'id,snippet',
      q: searchTerm
    }, function(err, response) {
      if (err) {
        console.log('The API returned an error: ' + err);
        return;
      }
      var channels = response.data.items;
      if (channels.length == 0) {
        console.log('No items found.');
      } else {
        console.log('This items\'s ID is %s. Its title is \'%s\', and ' ,
                    channels[0].id,
                    channels[0].snippet.title
                    );
      }
      console.log(channels.length);
      callback(channels);
    });
    //

  }

  module.exports ={
    getChannel
}

Я нашел этот документ об ошибке. Я кодирую в соответствии с указанными правилами.

С наилучшими пожеланиями,

Саурав

Ответы [ 2 ]

0 голосов
/ 22 апреля 2020

Проблема была с моим вспомогательным классом, который не был ожидаемой функцией.

Я внес изменения в свою вспомогательную функцию, чтобы она возвращала обещание, и она начала работать.

Ниже приведен обновленный код

 function askMusicPreferences(answer, convo, bot){


myDialog.ask('What would like to hear?', [
    {
        pattern: '.*',
        handler: async(response, convo, bot, message) => {
            try {
            var channels = await YoutubeHelper.getChannel(response);

            if (channels.length == 0) {

               await bot.say('No items found.');
            }
               else {
                await bot.say(`This items\'s ID is ${channels[0].id}. Its title is ${channels[0].snippet.title}`);
              }

            }catch (error){
                console.log( 'error occurred ', err);
            }


       // }
        // catch (err){
        //     console.log('error occurred', err);
        // }

    }
}
],  {key: 'name'});
}

My helper class

    /**
 * Lists the names and IDs of up to 10 files.
 *
 * 
 */

var {google} = require('googleapis');

var {myDialog} = require("./bot");


const getChannel = function getChannel(searchTerm) {
    return new Promise(function(resolve,reject) {

    var service = google.youtube({
      version : 'v3',
      auth : '<client id>'});


    service.search.list({
      part: 'id,snippet',
      q: searchTerm
    }, function(err, response) {
      if (err) {
        console.log('The API returned an error: ' + err);
        reject(err);
        return;
      }
      var channels = response.data.items;
      if (channels.length == 0) {
        console.log('No items found.');
      } else {
        console.log('This items\'s ID is %s. Its title is \'%s\', and ' ,
                    channels[0].id,
                    channels[0].snippet.title
                    );
      }
      console.log(channels.length);
      resolve(channels);
      //callback(channels);
    });
    //
  }); 

  }

  module.exports ={
    getChannel
}
0 голосов
/ 12 апреля 2020

Попробуйте поставить первую await функцию в блок try-catch :

myDialog.ask('What would like to hear?', [
  {
    pattern: '.*',
    handler: async (response, convo, bot) => {
      try {
        await YoutubeHelper.getChannel(response, convo, async function (channels) {
          console.log("value returned " + channels.length);
          try {
            await bot.say('Printing values'); //error comes here

            if (channels.length == 0) {
              await bot.say('No items found.');
            }
            else {
              await bot.say('This items\'s ID is %s. Its title is \'%s\', and ',
                channels[0].id,
                channels[0].snippet.title
              );
            }
          }
          catch (err) {
            console.log('error occurred', err);

          }
        });
      }
      catch (error) {
        console.log('----::error::----', error)
      }
    }
  }

], { key: 'name' });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...