module.exports 返回未定义

module.exports returning undefined

我正在尝试在“services/ibmWatson/index.js”中使用 IBM Watson API 制作翻译功能。我正确地收到了响应,但是当我 return 对“IncidentController.js”的响应时,它收到的是未定义的。

const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
const { IamAuthenticator } = require('ibm-watson/auth');

module.exports = {
    async translate(phrase, language) {

        const languageTranslator = new LanguageTranslatorV3({
            authenticator: new IamAuthenticator({ apikey: '<my_API_key>' }),
            url: 'https://gateway.watsonplatform.net/language-translator/api/',
            version: '2020-03-28',
        });

        await languageTranslator.translate(
            {
                text: phrase,
                source: 'pt',
                target: language
            })
            .then(response => {
                if(response.status=200){
                    console.log(response.result.translations);
                    return(response.result.translations);
                }
                return (["error"]);
            })
            .catch(err => {
                console.log('error: ', err);
                return (["error"]);
            });
    }
}

在上面的代码中 console.log(response.result.translations) returns 正确:

[ { translation: 'Dog run over.' },
  { translation: 'Castration' },
  { translation: 'Ticks' },
  { translation: 'Tuberculosis' } ]

在IncidentController.js中:

const Watson = require('../../src/services/ibmWatson');
const db_connection = require('../database/connection');

module.exports = {
        async index(request, response) {
            const incidents = await db_connection('incidents').join('ongs', 'ongs.id', '=', 'incidents.ong_id')
                .select([
                        'incidents.*',
                        'ongs.name',
                            'ongs.uf']
                    );

            const titles = [];
            incidents.forEach((incident) => { titles.push(incident.title) });

            const translated_titles = await Watson.translate(titles, "en");
            console.log(translated_titles);

            return response.json(incidents);
    }
}

在上面的代码中 console.log(response.result.translations) returns undefined

有什么问题吗?

您正在将 response.result.translations 返回到 then()response 回调。 由于您的 IncidentController 无法访问该回调,因此它 returns undefined。 这是解决此问题的一种方法:

// services/ibmWatson/index.js
translate(phrase, language) {
   return new Promise((resolve, reject) => {
      try {
         const response = await languageTranslator.translate({ /* options */ });
         resolve(response); // Return the translations
      } catch(error) {
         reject(error); // If there's an error, return the error
      }
   });
}
// IncidentController.js
async index() {
   // ...
   const translatedTitles = await Watson.translate(titles, "en");
   console.log(translatedTitles); // Should be working now
}

我希望我能帮助你或者至少引导你朝着正确的方向前进。