简体   繁体   中英

Return value from Google Cloud Translate API in Node JS

I'm playing with the Google Cloud Translate API using NodeJS. I can console.log the value returned from a promise. But I'm unsure how to pass that value into a template file like EJS. All that shows on screen is [object Promise]. Here is my code:

var express = require('express');
var app     = express();

app.set('view engine', 'ejs');

// Imports the Google Cloud client library
const Translate = require('@google-cloud/translate');
// Your Google Cloud Platform project ID
const projectId = process.env.GOOGLEPROJECTID;

// Instantiates a client
const translateClient = Translate({
  projectId: projectId
});

// The text to translate
const text = 'Hello, world!';
// The target language
const target = 'ru';

// Translates some text into Russian
let russianTranslate = translateClient.translate(text, target)
  .then((results) => {
    const translation = results[0];

    console.log(`Translation: ${translation}`);
    return {textToTranslate: `Text: ${text}`}
  });

app.get('/', function(req, res){
  res.render('index', { translation: russianTranslate });
});

app.listen(8080, function() {
  console.log('App Started!');
});

It console.logs out fine but I don't get the same value when I use EJS.

How can I fix this?

Resolve the promise first instead of passing it as is

The problem is that you do not actually pass the translated string to the template, but rather the promise object that will return the translation. This is why you get [object Promise] as a result.

In your code, the translated string is assigned to results[0] inside your callback function. This means you need to pass that variable to the renderer, but since it is only available inside your callback, you need to make sure it finishes first.

The easiest way to do that is to move any code that uses it inside the callback in .then() , and proceed from there.

// Translates some text into Russian
translateClient.translate(text, target)
  .then((results) => {

    app.get('/', function(req, res){
      res.render('index', { translation: results[0] });
    });

    app.listen(8080, function() {
      console.log('App Started!');
    });

  });

Disclaimer: this is untested 3AM back-of-the-envelope code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM